Java ProgramsOOPMultilevel Inheritance

Multilevel Inheritance in Java

intermediate·  OOP  ·  Inheritance

Problem

Multilevel inheritance chains classes together — a class extends a class, which itself extends another class — so the bottom class ends up inheriting from every ancestor up the chain, not just the one directly above it.

Create a Vehicle class extended by a Car class, which is itself extended by a SportsCar class, and confirm SportsCar inherits from both ancestors.

Input
new SportsCar() calling move(), drive(), and race()
Output
Vehicle moves Car drives SportsCar races

Java Program

Java
class Vehicle { void move() { System.out.println("Vehicle moves"); } } class Car extends Vehicle { void drive() { System.out.println("Car drives"); } } class SportsCar extends Car { void race() { System.out.println("SportsCar races"); } } public class MultilevelInheritanceDemo { public static void main(String[] args) { SportsCar sportsCar = new SportsCar(); sportsCar.move(); // inherited from Vehicle, two levels up sportsCar.drive(); // inherited from Car, one level up sportsCar.race(); // defined in SportsCar itself } }

Output

Vehicle moves Car drives SportsCar races

Core Logic

Chaining extends across three classes means each class only has to add what's new — everything from further up the chain comes along automatically.

How It Works
  1. 1class Car extends Vehicle makes Car inherit from Vehicle, exactly like single inheritance.
  2. 2class SportsCar extends Car adds one more link — SportsCar inherits from Car, which itself already inherits from Vehicle.
  3. 3A SportsCar object can call move(), declared all the way up in Vehicle, even though SportsCar never extends Vehicle directly.
  4. 4The same object can also call drive() from Car and race() from its own class, so all three levels' methods are available on it.
Calling move(), drive(), and race() on one SportsCar object reaches all three classes in the chain, printing one line from each.
💡

Key Point: Inheritance is transitive — SportsCar gets Vehicle's members through Car, without ever mentioning Vehicle in its own extends clause.

Key Concepts

chained extendsmulti-level hierarchytransitive inheritance

Related Programs