【发布时间】:2020-02-18 21:53:52
【问题描述】:
我想知道为什么 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 和对象可以看到值x 和PARENT.x。
此时为什么getX()选择PARENT.x而不是CHILD1.x?
通过覆盖方法this 也没有效果。在这种情况下,例如System.out.println(PC2); 在CHILD2 中始终使用getX(),无论您是在getY() 方法中写入return this.getX(); 还是return getX();。
有人可以总结一下这背后的系统吗?也许还考虑super?谢谢!
【问题讨论】:
标签: java inheritance subclass