Overriding là khả năng định nghĩa hành vi specific cho subclass type, nghĩa là subclass có thể implement method của parent class dựa trên yêu cầu của nó.
Về mặt OOP, overriding nghĩa là ghi đè chức năng của method hiện có.
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");
}
}
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
}
}
Kết quả
Animals can move Dogs can walk and run
Trong ví dụ trên, bạn thấy dù b kiểu Animal nhưng chạy method move của class Dog. Lý do: Compile-time kiểm tra reference type. Runtime, JVM xác định object type và chạy method của object đó. Do đó chương trình compile đúng vì Animal có method move. Runtime chạy method specific cho object.