Java中方法的動態分派或執行時多型


Java 中的執行時多型透過方法重寫來實現,其中子類重寫了其父類中的某個方法。被重寫的方法在父類中實際上是隱藏的,除非子類在重寫的方法中使用了 super 關鍵字,否則不會呼叫該方法。這種方法呼叫解析在執行時發生,被稱為動態方法派發機制。

示例

我們來看一個示例。

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

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

將會產生以下結果 −

輸出

Animals can move
Dogs can walk and run

在上例中,你可以看到儘管 b 是動物型別,但它執行的是“狗狗”類中的 move 方法。原因是:在編譯時,是對引用型別進行檢查。然而,在執行時,JVM 找出物件型別,並將執行屬於該特定物件的方法。

因此,在上例中,該程式會正確編譯,因為“動物”類具有 move 方法。然後,在執行時,它將執行特定於該物件的方法。

更新於: 2020 年 6 月 21 日

10K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.