Java ProgramsOOPHierarchical Inheritance

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. 1class Car extends Vehicle and class Bike extends Vehicle both inherit from the same Vehicle class, independently of each other.
  2. 2Car and Bike are siblings — neither extends the other, and neither has any special relationship beyond sharing Vehicle as a parent.
  3. 3Each subclass still adds its own distinct method — drive() for Car, ride() for Bike — alongside what it inherited.
  4. 4Calling fuel() on a Car object and on a Bike object both run the exact same inherited method from Vehicle.
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

Related Programs