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

Could you point me to the JLS section where it is specified that inherited methods will not act on subclasses re-defined variables?

你能给我指出 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;
  }
}

你还没有"re-defined"value。您在 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;
        }
    }
}