如果你覆盖一个类的子类中的一个字段,该子类有两个同名(不同类型)的字段? [英] If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

查看:26
本文介绍了如果你覆盖一个类的子类中的一个字段,该子类有两个同名(不同类型)的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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);
}

推荐答案

成员变量不能像方法一样被覆盖.您的类 BetaGama 中的 number 变量隐藏(不覆盖)成员变量 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆