Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It is a key feature of runtime polymorphism.
When a child class defines a method with the same name, return type, and parameters as a method in its parent class, the child version overrides the parent version.
// Parent class definition
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Child class overriding the method
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// Main class to demonstrate method overriding
class TestOverride {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Dog barks
Although the reference variable is of type Animal, the method of Dog class is executed because the object is created at runtime. This is called runtime polymorphism.
Select which object to instantiate at runtime to see how the output changes, even though the reference is always Animal.
@Override annotation for clarity