Method Overriding
Overview
Method Overriding occurs when a Child class provides a specific implementation for a method that is already provided by its Parent class. This allows the child class to drastically alter or completely replace the inherited behavior to suit its specific needs.
This is the mechanism that powers Runtime Polymorphism. To successfully override a method, the Child's method MUST have the exact same name, exact same parameters, and the exact same return type as the Parent's method.
It is an industry standard to place the @Override annotation immediately above the child's method. This instructs the compiler to verify that you are actually overriding a valid parent method, preventing silent bugs caused by typos.
Syntax
class BankAccount {
public double getInterestRate() {
return 2.0; // Standard rate
}
}
class PremiumAccount extends BankAccount {
// We override the parent's generic method with our specific logic
@Override
public double getInterestRate() {
return 5.5; // Premium rate!
}
}
public class Main {
public static void main(String[] args) {
BankAccount normal = new BankAccount();
System.out.println(normal.getInterestRate()); // Prints 2.0
// Polymorphism + Overriding
BankAccount vip = new PremiumAccount();
System.out.println(vip.getInterestRate()); // Prints 5.5
}
}Common Pitfalls
- Forgetting the
@Overrideannotation and making a typo. If the parent haspublic void calculate(), and you typepublic void caculate()in the child without the annotation, Java won't complain! It just thinks you created a brand new, unrelated method, and your polymorphic code will silently execute the parent's logic. - Trying to override a
private,static, orfinalmethod. Private methods are invisible to children. Static methods belong to the class, not the object (they can be hidden, but not dynamically overridden). Final methods are explicitly locked to prevent overriding.
Interview Questions
Yes, but you can only make it MORE accessible, never less. If the parent method is protected, the child's overridden method can be protected or public. If you try to make it private, the compiler will crash, as it violates the established inheritance contract.
Since Java 5, an overridden method can change the return type, BUT ONLY if the new return type is a direct Child of the original return type. For example, if the Parent returns an Animal, the Child's overridden method is allowed to return a Dog.
Real-World Example
In almost all modern Java applications, developers override the toString() method (which every class inherits from the ultimate root Object class). Instead of printing a useless memory address, overriding it allows you to print a clean JSON or text representation of the object.
public class User {
String name = "Alice";
@Override
public String toString() {
// Replaces the default memory address printout
return "User { name='" + name + "' }";
}
}Check Your Knowledge
Test your understanding of Method Overriding with these quick questions.