public class Test01 { public static void main(String[] args) { Father01 obj = new Son01(); System.out.println(obj); System.out.println(obj.name); }}class Father01 { public String name = "fu"; Father01() { System.out.println(this); System.out.println(this.name); }}class Son01 extends Father01 { public String name = "son";} 本人很不理解System.out.println(obj.name);的结果为什么是 fu 呢? Father01 obj = new Son01(); 这段代码只有一个对象,那就是new出来的Son01对象,obj指向的是Son01对象,为什么输出结果不是son而是fu?求大神解答,感激不尽
1 回答
qq_狼烟四起_0
TA贡献12条经验 获得超5个赞
Father01 obj = new Son01(); 的意思是在类Father01中实例化一个Son01()方法的对象。但是你的Father01类中没有Son01()方法,所以实例化的是父类的对象,最后执行主类中的两条printf,再输出一条fu。其实obj一直是父类的对象。
父类 xx = new 子类()定义的对象只能调用继承来的方法。就是父类中的方法
子类 xx = new 子类()定义的对象调用的是子类的方法,而不是父类的。
package test;
public class FatherNewSon {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
a ta = new b();
b tb = new b();
ta.test();
//ta.son();
tb.test();
tb.son();
}
}
class a {
public a() {
}
public void test() {
System.out.println(this.getClass().getName());
}
}
class b extends a {
public b() {
System.out.println(false);
}
public void son() {
System.out.println("son");
}
}ta.son是错误的方法
添加回答
举报
0/150
提交
取消
