Java 中的執行時多型性


方法覆蓋是執行時多型性的一個例子。在方法覆蓋中,子類覆蓋了與超類中籤名相同的某個方法。在編譯時,將檢查引用型別。但是,在執行時,JVM 找出物件型別,然後執行屬於該特定物件的方法。

示例

檢視以下示例來理解此概念 −

 活演示

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

更新於: 17-Jun-2020

15K+ 次瀏覽

啟動您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.