如果覆盖一个类的子类中的字段,该子类有两个同名(且类型不同)的字段?
我有 3 个类:
public class Alpha {
public Number number;
}
public class Beta extends Alpha {
public String number;
}
public class Gama extends Beta {
public int number;
}
为什么下面的代码可以编译?而且,为什么测试能够通过而没有任何运行时错误?
@Test
public void test() {
final Beta a = new Gama();
a.number = "its a string";
((Alpha) a).number = 13;
((Gama) a).number = 42;
assertEquals("its a string", a.number);
assertEquals(13, ((Alpha) a).number);
assertEquals(42, ((Gama) a).number);
}
I have 3 classes:
public class Alpha {
public Number number;
}
public class Beta extends Alpha {
public String number;
}
public class Gama extends Beta {
public int number;
}
Why does the following code compile? And, why does the test pass without any runtime errors?
@Test
public void test() {
final Beta a = new Gama();
a.number = "its a string";
((Alpha) a).number = 13;
((Gama) a).number = 42;
assertEquals("its a string", a.number);
assertEquals(13, ((Alpha) a).number);
assertEquals(42, ((Gama) a).number);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
成员变量不能像方法一样被重写。
Beta
和Gama
类中的number
变量隐藏(而不是覆盖)成员变量number超类的
。通过强制转换,您可以访问超类中的隐藏成员。
Member variables cannot be overridden like methods. The
number
variables in your classesBeta
andGama
are hiding (not overriding) the member variablenumber
of the superclass.By casting you can access the hidden member in the superclass.
字段不能被覆盖;它们一开始就不是多态访问的——您只是在每种情况下声明一个新字段。
它可以编译,因为在每种情况下,表达式的编译时类型足以确定您指的是哪个名为
number
的字段。在现实世界的编程中,您可以通过两种方法来避免这种情况:
Fields can't be overridden; they're not accessed polymorphically in the first place - you're just declaring a new field in each case.
It compiles because in each case the compile-time type of the expression is enough to determine which field called
number
you mean.In real-world programming, you would avoid this by two means:
Java 隐藏字段
当后继类的字段与超类的字段名称相同时,称为 - 隐藏字段 strong>
Java的字段不支持多态性,也不考虑字段的类型
[Swift重写属性]
Java Hiding a field
When successor has a field with the same name as a superclass's field it is called - Hiding a field
Java's field does not support polymorphism and does not take a field's type into account
[Swift override property]
作为解决方法,您可以使用 getter 方法:
As a workaround, you can use getter methods: