Java Method Overriding - Rules & Example
Method overriding occurs when a subclass provides a specific implementation of a method
already defined in its superclass. The call to the method is resolved at runtime based
on the actual object type, enabling runtime polymorphism.
Rules:
1. Same method name, parameter list, and compatible return type.
2. Must be in a subclass (inheritance required).
3. Access modifier cannot be more restrictive than in superclass.
4. Cannot override static, final, or private methods.
5. May throw narrower or fewer checked exceptions.
6. Use @Override annotation to avoid mistakes.
Example:
class Animal {
public void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
public void sound() {
[Link]("Cat meows");
}
}
public class TestOverriding {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Dog();
Animal a3 = new Cat();
[Link](); // Animal makes a sound
[Link](); // Dog barks
[Link](); // Cat meows
}
}
[Image could not be loaded: HTTPSConnectionPool(host='[Link]', port=443): Max retries exceeded with url: