为什么 this.<variable> 或者 this.<method()> in Parent Class 没有效果? Java

Why does this.<variable> or this.<method()> in Parent Class have no effect? Java

我想知道为什么 this.(...) 在这种情况下没有效果。以下是我的考试任务:

class PARENT {
    public int x;
    public PARENT(int a)    {this.x = a;}

    public int getX()   {return this.x;}
    public int getY()   {return this.getX();}
}

class CHILD1 extends PARENT {
    public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}

class CHILD2 extends PARENT {
    public CHILD2(int c)    {super(c);}

    public int getX()   {return 5;}
}

public class ThisTestMain {
    public static void main(String[] args)  {
        PARENT PP = new PARENT(10);
        PARENT PC1 = new CHILD1(100);
        PARENT PC2 = new CHILD2(1000);
        System.out.println(PP.getY());
        System.out.println(PC1.getY());
        System.out.println(PC2.getY());

        CHILD1 CC = new CHILD1(10);
        System.out.println(CC.getY());
    }
}

输出为:

10
100
5
10

我现在的问题是为什么 System.out.println(PC1); 的输出不是 200。因为当我在 IntelliJ 中调试代码时,我可以看到 this 有参考 CHILD1@799 并且对象可以看到值 xPARENT.x

此时为什么 getX() 选择 PARENT.x 而不是 CHILD1.x

通过覆盖方法 this 也没有效果。在这种情况下,例如 System.out.println(PC2); 始终使用 CHILD2 中的 getX(),无论您是在 getY() 方法中编写 return this.getX(); 还是 return getX();.

有人可以总结一下背后的系统吗?也许也在考虑 super?谢谢!

CHILD1 定义了一个名为 x 的新字段,即 shadows 中的字段 x PARENT。删除字段。喜欢

class CHILD1 extends PARENT {
    // public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}

在 CHILD1 中,您没有重写方法。

因此,当您调用 getY() 时,它会从 PARENT 调用 getX()。来自 PARENT 的方法不知道其子 类.

中的变量

您必须覆盖 CHILD1 中的方法 getX() 才能访问变量 CHILD1.x。