Method Overriding

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Method Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its parent class.
  • It is the foundation of Runtime Polymorphism (Dynamic Binding).
  • The overridden method in the child class must have the exact same signature (name and parameters) as the method in the parent class.

Concept

When a parent class has a method (like animal.makeSound()), it might provide a generic implementation. The child class (Dog) can override that method to provide a specific implementation (Bark!).

The @Override annotation is optional but highly recommended. It tells the compiler to double-check that you are actually overriding a parent method (and didn’t just make a typo in the method name).

Important Rules

  1. Access Modifiers: The overriding method cannot have a more restrictive access modifier than the parent method. (If parent is protected, child can be protected or public, but not private).
  2. Exceptions: The overriding method cannot throw new or broader checked exceptions than the parent method.

Examples

class Vehicle {
    protected void startEngine() {
        System.out.println("Starting a generic engine.");
    }
}

class Car extends Vehicle {
    // Overriding the parent method
    @Override
    public void startEngine() {
        System.out.println("Starting car engine: Vroom!");
    }
    
    /* 
    ILLEGAL OVERRIDE (Compile Error):
    @Override
    private void startEngine() { } 
    Reason: Cannot reduce visibility from protected to private.
    */
}

Interview Questions

Q: Can you override a static method?
A: No. Static methods belong to the class, not the instance. If a subclass defines a static method with the same signature, it hides the parent’s method (Method Hiding), but it does not override it. Polymorphism doesn’t apply to static methods.

Q: Can you override a private or final method?
A: No. private methods are completely invisible to the child class, so there is nothing to override. final methods explicitly forbid overriding as a language feature to protect the implementation.