public class Test05 {
public static void main(String[] args) {
Father obj = new Son();
System.out.println(obj.name);//这里其实是子类的对象,子类的对象.name怎么会访问到父类的属性了呢?
System.out.println("---------");
Son obj2 = new Son();
System.out.println(obj2.name);
Father obj = new Son();
System.out.println(obj.name);//这里输出的却是子类字段
}
}
class Father{
public String name = "父类字段";
Father(){
System.out.println(this);//这里打印的是子类的内存地址.
System.out.println(this.name);//这里打印的是父类的成员变量
this.show();//这里是访问子类的方法
}
public void show(){
System.out.println(this.name);
}
}
class Son extends Father{
public String name = "子类字段";
public void show(){
System.out.println(this.name);
}
}
上面打印的结果:
Son@1542a75
父类字段
null
父类字段
Son@af993e
父类字段
null
子类字段
我的疑惑是:
在父类的构造方法打印的this是son的对象.
this.name 不应该是访问son对象的属性name吗?