Java Tutorial
🔍
Java ProgramsOOPInheritance & Method Overriding

Inheritance & Method Overriding in Java

intermediate·  OOP  ·  Inheritance

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

Java
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

The dog barks

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.

How It Works
  1. 1class Dog extends Animal makes Dog a subclass that inherits everything Animal defines.
  2. 2@Override void sound() replaces the inherited method with Dog-specific behavior; the annotation lets the compiler catch signature mismatches.
  3. 3Animal a = new Dog(); declares the variable as type Animal, but the object it points to is actually a Dog.
  4. 4When a.sound() is called, Java resolves the method using the object's actual runtime type, not the variable's declared type.
Even though 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

extends@Overrideruntime polymorphism

Related Programs