การ override เมธอดเป็นตัวอย่างของพอลิморฟิซึมรันไทม์ ในการ override เมธอด คลาสย่อยจะ override เมธอดที่มีลายเซ็นเดียวกับในคลาสแม่ของมัน ในขณะคอมไพล์ การตรวจสอบทำบนประเภทอ้างอิง อย่างไรก็ตาม ในรันไทม์ 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