Method overriding là ví dụ của runtime polymorphism. Trong overriding, subclass override method cùng signature với superclass. Compile-time kiểm tra trên reference type. Tuy nhiên runtime, JVM xác định object type và chạy method thuộc object đó.
Chúng ta có thể override method ở bất kỳ cấp nào của multilevel inheritance. Xem ví dụ:
Ví dụ
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");
}
}
class Puppy extends Dog {
public void move() {
System.out.println("Puppy can move.");
}
}
public class Tester {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Puppy(); // Animal reference but Puppy object
a.move(); // runs method in Animal class
b.move(); // runs method in Puppy class
}
}
Kết quả
Animals can move Puppy can move.