在以下代码示例中:
class Parent {
int x =5;
public Integer aMethod(){
System.out.print("Parent.aMthod ");
return x;
}
}
class Child extends Parent {
int x =6;
public Integer aMethod(){
System.out.print("Child.aMthod ");
return x;
}
}
class ZiggyTest2{
public static void main(String[] args){
Parent p = new Child();
Child c = new Child();
System.out.println(p.x + " " + c.x);
System.out.println(p.aMethod() + " \n");
System.out.println(c.aMethod() + " \n");
}
}
输出结果为:
5 6
Child.aMthod 6
Child.aMthod 6
当p.x打印6时,为什么p.aMethod()
没有打印6?
谢谢。
编辑
糟糕,有一个小笔误:问题应该是“当p.x打印5时,为什么p.aMethod()没有打印5?”- 感谢@thinksteep。