java中的多态性

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?

求大神解答,感激不尽

月亮岛Superman
浏览 1140回答 1
1回答

qq_狼烟四起_0

 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是错误的方法
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java