Inheritance is an essential pillar of Object-Oriented Programming that allows a new class (known as the child / subclass / derived class) to inherit the state fields and behavioral methods of an existing class (known as the parent / superclass / base class).
B extends A).C extends B, and B extends A).B extends A and C extends A).Suppose Class B and Class C both inherit from Class A and override display(). If Class D were permitted to extend both B and C, the compiler would have no way to determine which version of display() to inherit. To preserve language simplicity and safety, Java prohibits multiple class inheritance.
super KeywordLet us examine a vehicle hierarchy showcasing extends and the three roles of super:
// Superclass (Parent)
class Vehicle {
protected String registrationNumber;
protected int maxSpeed;
// Parent Constructor
public Vehicle(String regNum, int maxSpeed) {
this.registrationNumber = regNum;
this.maxSpeed = maxSpeed;
}
public void startEngine() {
System.out.println("Vehicle engine ignited. Max speed: " + maxSpeed + " km/h");
}
}
// Subclass (Child)
class ElectricCar extends Vehicle {
private int batteryCapacityKwh;
public ElectricCar(String regNum, int maxSpeed, int batteryCapacity) {
// 1. Invoking Parent Constructor using super()
super(regNum, maxSpeed);
this.batteryCapacityKwh = batteryCapacity;
}
// Overriding Parent Method
@Override
public void startEngine() {
// 2. Invoking Parent's Original Method using super.
super.startEngine();
System.out.println("Electric inverter active! Battery: " + batteryCapacityKwh + " kWh");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
ElectricCar tesla = new ElectricCar("MH-12-EV-9999", 250, 85);
tesla.startEngine();
}
}
Exam Question: "What is the ultimate root class of all classes in Java?"
Answer: java.lang.Object! Every class in Java directly or indirectly inherits from Object. If a class does not explicitly write extends, the compiler automatically inserts extends Object. This guarantees that all objects inherit foundational methods like toString(), equals(), hashCode(), and getClass().
Now let us explore Polymorphism, Dynamic Method Dispatch, and Runtime Overriding. Proceed to: Java Polymorphism & Overriding →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Dynamic method dispatch.
Multiple inheritance via interfaces.
Superclass constructor calls.
Protected and public inheritance.