If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

烂漫一生 提交于 2019-11-26 05:56:28

问题


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

回答1:


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.




回答2:


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:

  • Common-sense: shadowing fields makes your code harder to read, so just don't do it
  • Visibility: if you make all your fields private, subclasses won't know about them anyway


来源:https://stackoverflow.com/questions/9414990/if-you-overwrite-a-field-in-a-subclass-of-a-class-the-subclass-has-two-fields-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!