iT邦幫忙

DAY 30
0

Java重點學習筆記系列 第 30

Java重點筆記 27:Java物件導向之覆寫(Overriding) - 調用上級方法

上一篇介紹了覆寫(Overriding),可在子類別(Sub Class)中覆寫父類別(Super Class)的方法。但有時我們需要直接使用父類別的方法,Java為此提供了super關鍵字用來指向父類別。用法非常簡單,super.method() 即可使用父類別中的方法。

請看以下例子:

class Animal{

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

class Dog extends Animal{

   public void move(){
      super.move(); // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){

      Animal b = new Dog(); // Animal reference but Dog object
      b.move(); //Runs the method in Dog class

   }
}

輸出如下:

Animals can move
Dogs can walk and run

by Zack Live


上一篇
Java重點筆記 26:Java物件導向之覆寫(Overriding)
系列文
Java重點學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言