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
class Car extends VehiclemakesCarinherit fromVehicle, exactly like single inheritance. - 2
class SportsCar extends Caradds one more link —SportsCarinherits fromCar, which itself already inherits fromVehicle. - 3A
SportsCarobject can callmove(), declared all the way up inVehicle, even thoughSportsCarnever extendsVehicledirectly. - 4The same object can also call
drive()fromCarandrace()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