初步认识Java中的向上转型

package object;

 class Animal {
         public void eat(){
                   System.out.println("animal eatting...");
         }
}

class Bird extends Animal{
         public void eat(){
                   System.out.println("bird eatting...");
         }

         public void fly(){
                   System.out.println("bird flying...");
         }
}

public class E05_DataOnly2{      

         public static void main(String[] args) {

                   Animal b=new Bird(); //向上转型
                   b.eat();
                // b.fly();  //此处提示在Animal中没有定义fly方法。
         }
}/* Output:
bird eatting...
*///:~

子类对象当成父类对象,只能调用父类的成员,如果子类重写了父类的方法就根据这个引用指向调用子类重写的这个方法(这个方法就是覆盖override)。这个调用过程就称为“动态绑定”。这就是输出 bird eatting...而不是animal eatting...的原因。

posted on 2017-08-30 18:37  dannerl  阅读(155)  评论(0)    收藏  举报