您能否指出 JLS 部分,其中指定继承的方法不会作用于子类重新定义的变量?
即以下代码的输出是“value is 3”,而不是“value is 5”。
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int value = 5;
}
}
最佳答案
您尚未“重新定义”值
。您已在 PlayGroundSon
中创建了一个完全独立的字段,并且该字段恰好具有相同的名称。
您只能重写方法。如果您希望程序打印 5
,则必须重写 getValue()
方法。我还更改了 PlayGroundSon
中的变量名称,以强调它与 PlayGround
中的 value
不同。
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int sonValue = 5;
@Override
public int getValue() {
return sonValue;
}
}
}
关于java - 您能否指出 JLS 部分,其中指定继承的方法不会作用于子类重新定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29232067/