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 是動物型別,它也會在 Dog 類中執行 move 方法。原因是:在編譯期,對引用型別進行了檢查。但是,在執行時,JVM 會找出物件型別,並執行屬於特定物件的方法。
因此,在上面的示例中,該程式將正確編譯,因為 Animal 類具有 move 方法。然後,在執行時,它會為該物件執行特定方法。
廣告