Java:调用与接口字段冲突的抽象类的非静态字段
如何显示抽象类 Confused("ConfusedValue") 中“name”非静态字段的值? 我尝试了3种方法,但都有错误。我只能显示 Confuslable 的名称值(“ConfusableValue”)
interface Confusable {
String name = "ConfusableValue";
String confuse();
}
abstract class Confused {
String name = "ConfusedValue";
abstract Object confuse();
}
public class Test extends Confused implements Confusable {
public static void main(String[] args) {
Test a = new Test();
// --- OK
System.out.println("Confusable.name: " + Confusable.name);
// --- Errors
System.out.println("name: " + name); // Error : The field name is ambiguous
System.out.println("Confused.name: " + Confused.name); // Error : Cannot make a static reference to the non-static field Confused.name
System.out.println("a.name: " + a.name); // Error : The field a.name is ambiguous
}
}
How to display the value of the "name" non-static field from the abstract class Confused("ConfusedValue") ?
I tried 3 ways, but all have errors. I can display only the Confuslable's name value("ConfusableValue")
interface Confusable {
String name = "ConfusableValue";
String confuse();
}
abstract class Confused {
String name = "ConfusedValue";
abstract Object confuse();
}
public class Test extends Confused implements Confusable {
public static void main(String[] args) {
Test a = new Test();
// --- OK
System.out.println("Confusable.name: " + Confusable.name);
// --- Errors
System.out.println("name: " + name); // Error : The field name is ambiguous
System.out.println("Confused.name: " + Confused.name); // Error : Cannot make a static reference to the non-static field Confused.name
System.out.println("a.name: " + a.name); // Error : The field a.name is ambiguous
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字段名称不会被继承。他们只是互相影子。这是编译器关心的问题,但就运行时而言,它们都是独立存在的,只是碰巧共享一个名称。
因此,我们只需要使类型对于编译器来说看起来正确,并且我们可以通过显式向上转换来做到这一点。这些是向上转换(即扩大转换),因此它们是安全的并且保证会成功。
Field names are not inherited. They merely shadow each other. That's a concern for the compiler, but as far as the runtime is concerned, they both exist independently and just so happen to share a name.
So we just need to make the types look right to the compiler, and we can do that with explicit upcasts. These are upcasts (i.e. widening conversions), so they're safe and guaranteed to succeed.