Inheritance is the mechanism in OOP by which one class (the child or subclass) acquires the properties and methods of another class (the parent or superclass). It represents an "IS-A" relationship.
A Dog IS-A Animal. A Car IS-A Vehicle. The child class inherits everything from the parent and can add its own unique features on top.
Without inheritance, if you need a Car, Truck, and Motorcycle class that all share common attributes (speed, fuelLevel) and methods (accelerate(), brake()), you would copy-paste the same code three times. If a bug is found in accelerate(), you must fix it in three places.
With inheritance, you define the shared code once in a Vehicle parent class, and all three child classes inherit it automatically. Fix the bug once, and it's fixed everywhere.
class Vehicle {
int speed;
void accelerate() { speed += 10; }
void brake() { speed -= 10; }
}
class Car extends Vehicle {
int numDoors; // Car-specific attribute
void openTrunk() { /* Car-specific behavior */ }
}
class Motorcycle extends Vehicle {
boolean hasSidecar; // Motorcycle-specific attribute
}
A child class inherits from exactly one parent class. This is the most common and simplest form.
Car extends VehicleA child class inherits from a parent, which itself inherits from a grandparent. This forms a chain.
SportsCar extends Car extends Vehicleclass Vehicle { void start() {} }
class Car extends Vehicle { void openTrunk() {} }
class SportsCar extends Car { void activateTurbo() {} }
// SportsCar has access to start(), openTrunk(), AND activateTurbo()
Multiple child classes inherit from a single parent class. This forms a tree structure.
Car extends Vehicle, Truck extends Vehicle, Motorcycle extends VehicleA child class inherits from two or more parent classes simultaneously.
FlyingCar extends Car, AirplaneMultiple inheritance creates a critical ambiguity called the Diamond Problem. If both Car and Airplane have a method called move(), which version does FlyingCar inherit?
Because of this ambiguity:
A combination of two or more types of inheritance. For example, combining hierarchical and multiple inheritance. Like multiple inheritance, it can lead to the Diamond Problem and is generally avoided in Java.
super KeywordThe super keyword in Java is a reference variable used to refer to the immediate parent class object.
class Animal {
String name;
Animal(String name) { this.name = name; }
void speak() { System.out.println("..."); }
}
class Dog extends Animal {
Dog(String name) {
super(name); // Calls the parent's constructor
}
void speak() {
super.speak(); // Calls the parent's speak() method
System.out.println("Woof!");
}
}