Skip to content
C

Method Overriding

Method overriding happens when a subclass provides its own specific implementation of a method that is already defined in its parent class, using the exact same method name and parameters.


1. What is Method Overriding?

Method overriding happens when a subclass provides its own specific implementation of a method that is already defined in its parent class, using the exact same method name and parameters.

2. Why is it used?

It lets a subclass customize or replace inherited behaviour to suit its own specific needs, while still keeping the same method name so it can be called consistently across related classes.

3. Real-Life Example

Think of a general "make sound" instruction for animals, where a dog barks and a cat meows. Each animal overrides the general idea of "making sound" with its own specific version, while the underlying instruction name stays the same.

4. Syntax

java
class Parent { void methodName() { } } class Child extends Parent { @Override void methodName() { } }

5. Example Program

java
class Animal { void makeSound() { System.out.println("Some generic animal sound"); } } class Dog extends Animal { @Override void makeSound() { System.out.println("Bark"); } } public class OverridingDemo { public static void main(String[] args) { Animal a = new Dog(); a.makeSound(); } }

Output:

Bark

6. Key Points to Remember

  • Overriding is resolved at runtime, based on the actual object, not the reference type — this is called "runtime polymorphism."
  • The overriding method must have the same name, same parameters, and a compatible return type as the parent's method.
  • The @Override annotation isn't mandatory but is strongly recommended, since it helps catch mistakes at compile-time.