Method Overriding
Overview
While Overloading is about using the same name with *different* inputs, Method Overriding is about replacing a parent's method entirely.
If a parent `Animal` class has a `makeSound()` method that prints 'Grrr', but your child `Dog` class wants to print 'Woof', the Dog class can Override (crush and replace) the parent's method with its own version.
1. The Rules of Overriding
To override a parent method, your child method must have the EXACT same name, EXACT same return type, and EXACT same parameters.
2. The @Override Annotation
Always write `@Override` above your overridden method. It's a sticky note that tells Java: 'I am trying to replace a parent method. If I made a typo, please warn me!'
Syntax
The Dog replaces the generic Animal sound with a bark.
class Animal {
public void makeSound() {
System.out.println("Generic animal noise...");
}
}
class Dog extends Animal {
// We override (replace) the parent's version
@Override
public void makeSound() {
System.out.println("Woof woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Prints: Woof woof!
}
}Common Pitfalls
- Forgetting the `@Override` annotation and making a typo (like `makesound()` with a lowercase s). Java will just think you created a brand new method, and the override will fail silently.
Interview Tips
- Overriding is known as 'Run-Time Polymorphism'. Java waits until the program is actually running to look at the object in memory and decide which overridden method to trigger.
Real-World Example
Overriding is essential in games. A generic `Enemy` class has an `attack()` method, but `Zombie` and `Vampire` override it to attack in their unique ways.
class Zombie extends Enemy {
@Override
public void attack() {
System.out.println("Zombie bites you!");
}
}