java - 您能否指出 JLS 部分,其中指定继承的方法不会作用于子类重新定义的变量?

标签 java inheritance

您能否指出 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/

相关文章:

在两个类之间快速共享信息

Java:接口(interface)之前的 protected 方法

java - 继承Java私有(private)成员

java - 如何有效地更新数据库中的实体?

java - 这是好的编程习惯吗?构造函数和实例变量

java - 一次合并排序 3 个子数组

java - 如何避免此 NullPointerException

java - Java中synchronized/volatile的变量可见性影响到什么程度

c++ - union 虚拟继承

C# 扩展接口(interface)实现作为参数来委托(delegate)采用基接口(interface)