Hierarchical Inheritance in Java
intermediate· OOP · Inheritance
Problem
Hierarchical inheritance is the opposite shape from multilevel inheritance — instead of a chain, one single parent class is extended independently by more than one subclass, each unrelated to the others.
Create a Vehicle class extended separately by both a Car class and a Bike class, and confirm each inherits from Vehicle independently.
Input
new Car() and new Bike(), each calling fuel() alongside their own method
Output
Vehicle needs fuel
Car drives on roads
Vehicle needs fuel
Bike rides on roads
Java Program
Java
class Vehicle {
void fuel() {
System.out.println("Vehicle needs fuel");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car drives on roads");
}
}
class Bike extends Vehicle {
void ride() {
System.out.println("Bike rides on roads");
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Car car = new Car();
Bike bike = new Bike();
car.fuel();
car.drive();
bike.fuel();
bike.ride();
}
}Output
Vehicle needs fuel
Car drives on roads
Vehicle needs fuel
Bike rides on roads
Core Logic
Extending the same parent class from two separate subclasses gives both of them the parent's members, without either subclass knowing the other exists.
How It Works
- 1
class Car extends Vehicleandclass Bike extends Vehicleboth inherit from the sameVehicleclass, independently of each other. - 2
CarandBikeare siblings — neither extends the other, and neither has any special relationship beyond sharingVehicleas a parent. - 3Each subclass still adds its own distinct method —
drive()forCar,ride()forBike— alongside what it inherited. - 4Calling
fuel()on aCarobject and on aBikeobject both run the exact same inherited method fromVehicle.
Both a
Car and a Bike object print "Vehicle needs fuel" from the shared parent method, then each prints its own subclass-specific line.💡
Key Point: Both subclasses reuse the identical fuel() method from Vehicle — nothing about it changes between them, since neither overrides it.
Key Concepts
shared parent classsibling subclassesindependent inheritance