大家看看这个java程序

来源:百度知道 编辑:UC知道 时间:2024/05/18 07:37:33
public class TestChildParent {
public static void main(String args[]){
Parent c1=new Child();
System.out.println(c1.someMethod());
System.out.println(c1.aValue);
}

}

class Child extends Parent{
int aValue;
int someMethod(){
aValue=super.aValue+1;
return super.someMethod()+aValue;
}
}
class Parent{
int aValue=1;
int someMethod(){
return aValue;
}
}

结果是3,1,为什么不是3,2


这个东西就要记住一句话了
子类的方法,父类的属性

子类只能override父类的方法,但是对于父类引用的属性,就没有办法了。
所以在最后输出的时候,输出的是父类的属性。

Parent c1=new Child();
此时,c1.aValue = 0 (默认值),c1.super.aValue = 1 (初始化)。

System.out.println(c1.someMethod());
在 c1.someMethod() 里面:
aValue=super.aValue+1; // aValue = 1+1 = 2,这是 c1.aValue
return super.someMethod()+aValue; // return 1+2
因此输出3.
此时,c1.aValue = 2, c1.super.aValue = 1.

System.out.println(c1.aValue);
输出2.

对楼上两位的回答做个补充,在继承的时候我们一定要尽量避免属性的重名,这样能避免很多不必要的麻烦