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