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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP