Inheritance & Method Overriding in Java
Problem
Method overriding lets a subclass provide its own implementation of a method already defined in its parent class.
Create a base Animal class and a Dog subclass that overrides its behavior.
Java Program
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
// Overrides Animal's version with Dog-specific behavior
System.out.println("The dog barks");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Declared as Animal, but the actual object is a Dog
Animal a = new Dog();
// Java resolves sound() using the object's real (runtime) type
a.sound();
}
}Output
Core Logic
This is runtime polymorphism in action — a subclass overrides a parent method, and Java picks the subclass's version even when the reference is typed as the parent.
- 1
class Dog extends AnimalmakesDoga subclass that inherits everythingAnimaldefines. - 2
@Override void sound()replaces the inherited method with Dog-specific behavior; the annotation lets the compiler catch signature mismatches. - 3
Animal a = new Dog();declares the variable as typeAnimal, but the object it points to is actually aDog. - 4When
a.sound()is called, Java resolves the method using the object's actual runtime type, not the variable's declared type.
a is declared Animal, calling a.sound() prints "The dog barks", not a generic Animal message.Key Point: This is dynamic method dispatch — the JVM decides which overridden method to run based on the object's real class, at runtime.
Key Concepts
Interview Questions
What rules must an overriding method follow?
The same name and parameter list, a return type that is the same or a subtype, and access that is no more restrictive than the parent's. @Override makes the compiler check all of this.
How do you call the parent's version of an overridden method?
Use super.methodName(...). A common pattern is to extend the parent's behaviour rather than replace it completely.