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.