如果覆盖类的子类中的字段,子类有两个具有相同名称(和不同类型)的字段? [英] If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?
本文介绍了如果覆盖类的子类中的字段,子类有两个具有相同名称(和不同类型)的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个课程:
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);
}
推荐答案
成员变量不能被覆盖方法。类中的数字
变量 Beta
和 Gama
是隐藏(不覆盖)超类的成员变量 number
。
Member variables cannot be overridden like methods. The number
variables in your classes Beta
and Gama
are hiding (not overriding) the member variable number
of the superclass.
通过强制转换你可以访问超类中的隐藏成员。
By casting you can access the hidden member in the superclass.
这篇关于如果覆盖类的子类中的字段,子类有两个具有相同名称(和不同类型)的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文