gpt4 book ai didi

java - 为什么不能使用 super 关键字引用接口(interface)变量

转载 作者:行者123 更新时间:2023-12-02 08:24:03 26 4
gpt4 key购买 nike

我是java新手,据我所知,通常我们使用superthis关键字来引用父类(super class)属性。我们也不能在静态上下文(静态方法)中使用 thissuper 关键字。但我有一个问题。我使用匿名类来使用接口(interface),如下所示。我尝试从匿名类内部引用 number 变量(位于接口(interface)中)。但即使它不是静态上下文,我也无法使用 super 关键字引用数字。问题是什么?。我的代码如下。

    interface Age{
public static final int number =25;
public abstract int getAge();
}

public class Main {
public static void main(String[] args) {
Age age = new Age(){
public int getAge(){
int number = super.number;//compile error
//why cannot use super keyword in here to refer number variable
return number;
}
};
age.getAge();
}
}

最佳答案

super关键字指的是父类,而不是任何接口(interface)。在您提供的代码中,Age是一个接口(interface)。无论您查看的是匿名类还是命名类,您都会看到相同的行为。

如果您想知道为什么语言设计者决定不允许 super提到接口(interface),Aggragoth 对此进行了评论:一个类可以实现多个接口(interface),因此如果它们每个都有一个名为 number 的成员编译器不可能确定哪个接口(interface)是 number您试图用 super.number 来引用.

关于java - 为什么不能使用 super 关键字引用接口(interface)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com