← Back to Chapters

Method Overriding in Java

? Method Overriding in Java

? Quick Overview

Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It is a key feature of runtime polymorphism.

? Key Concepts

  • Method signature must be the same
  • Inheritance is required
  • Decision is made at runtime
  • Uses dynamic method dispatch

? Syntax / Theory

When a child class defines a method with the same name, return type, and parameters as a method in its parent class, the child version overrides the parent version.

? View Code Example
// Parent class definition
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
? View Code Example
// Child class overriding the method
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
? View Code Example
// Main class to demonstrate method overriding
class TestOverride {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}

?️ Output

Dog barks

? Explanation

Although the reference variable is of type Animal, the method of Dog class is executed because the object is created at runtime. This is called runtime polymorphism.

? Interactive Simulation

Select which object to instantiate at runtime to see how the output changes, even though the reference is always Animal.

Animal obj = new Animal();
obj.sound();

// Output: Animal makes a sound

✅ Tips & Best Practices

  • Use @Override annotation for clarity
  • Access modifier cannot be more restrictive
  • Static methods cannot be overridden

? Try It Yourself

  • Create a Shape class with a draw() method
  • Override draw() in Circle and Rectangle classes
  • Call methods using parent class reference