iT邦幫忙

DAY 29
0

Java重點學習筆記系列 第 29

Java重點筆記 26:Java物件導向之覆寫(Overriding)

子類別繼承父類別後,可使用父類別的方法(除了private的)。但有時父類別的方法無法完全符合子類別的要求,這時子類別可覆寫父類別的方法。

請看以下例子:

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object
    Dog c = new Dog(); // Dog reference and object

      a.move();// runs the method in Animal class

      b.move();// runs the method in Dog class

      c.move();// runs the method in Dog class
   }
}

輸出如下:

Animals can move
Dogs can walk and run
Dogs can walk and run

由於 b 指向 Dog Class 所以會執行 Dog Class 中的方法。

同樣方式,若 Dog Class 增加了一個 Animal Class 裡沒有的方法(例如 bark() ),且用 b 來執行該方法( b.bark() )則會出錯,因為 b (Animal Class)沒有這個方法。

by Zack Live


上一篇
Java重點筆記 25:Java物件導向之繼承(Inheritance)2 - implements
下一篇
Java重點筆記 27:Java物件導向之覆寫(Overriding) - 調用上級方法
系列文
Java重點學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言