Lesson 6 of 9
Composition Over Inheritance
'Favour object composition over class inheritance' is one of the most important principles in OOP. Inheritance creates tight coupling - a deep hierarchy is rigid and fragile. Composition (a class HAS-A reference to another object and delegates to it) is more flexible, testable, and maintainable.
The Problem with Deep Inheritance
- Deep hierarchies are fragile - a parent change breaks all descendants.
- Subclasses inherit ALL parent methods including those they don't need.
- 'Gorilla Banana Problem' - you wanted a banana, you got the gorilla holding the banana AND the entire jungle.
- Inheritance couples implementation - changing the superclass requires understanding all subclasses.
- Composition is more testable - you can mock/stub the composed object in unit tests.
Composition vs Inheritance
// ❌ Deep inheritance - fragile
class Vehicle { void start() {...} void stop() {...} }
class LandVehicle extends Vehicle { void drive() {...} }
class Car extends LandVehicle { void honk() {...} }
class ElectricCar extends Car { void charge() {...} }
// What about a FlyingCar? HybridVehicle? The tree breaks.
// ✅ Composition - HAS-A, flexible
// Behaviour as injectable components
public interface Engine {
void start();
void stop();
default String getType() { return "Engine"; }
}
public class GasEngine implements Engine {
@Override public void start() { System.out.println("Gas engine starts: VROOM"); }
@Override public void stop() { System.out.println("Gas engine stops"); }
@Override public String getType() { return "Gas"; }
}
public class ElectricMotor implements Engine {
private int batteryPercent = 100;
@Override public void start() { System.out.println("Electric motor: silent start"); }
@Override public void stop() { System.out.println("Electric motor stops"); }
@Override public String getType() { return "Electric"; }
}
// Car HAS-AN Engine (injected)
public class Car {
private final String model;
private final Engine engine; // composition - delegates engine behaviour
private boolean running;
public Car(String model, Engine engine) {
this.model = model;
this.engine = engine; // engine is injected - easily swappable!
}
public void start() {
engine.start(); // delegate to composed object
running = true;
System.out.println(model + " is running on " + engine.getType() + " engine");
}
public void stop() { engine.stop(); running = false; }
}
// Usage - swap engine type without changing Car class
Car tesla = new Car("Tesla Model 3", new ElectricMotor());
Car bmw = new Car("BMW M3", new GasEngine());
tesla.start(); // Electric motor: silent start | Tesla Model 3 is running on Electric
bmw.start(); // Gas engine starts: VROOM | BMW M3 is running on Gas engine
// In the Library: BorrowingPolicy as composition
public class Book extends LibraryItem {
private final BorrowingPolicy policy; // composed, swappable
public Book(String isbn, String title, BorrowingPolicy policy) {
super(isbn, title);
this.policy = policy;
}
@Override
public double calculateLateFee(int daysLate) {
return policy.calculateFee(daysLate); // delegate
}
}Quick Quiz
Tip
Tip
Practice Composition Over Inheritance in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Composition Over Inheritance
Practice Task
Note
Practice Task - (1) Write a working example of Composition Over Inheritance from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Composition Over Inheritance is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- 'Favour object composition over class inheritance' is one of the most important principles in OOP.
- Deep hierarchies are fragile - a parent change breaks all descendants.
- Subclasses inherit ALL parent methods including those they don't need.
- 'Gorilla Banana Problem' - you wanted a banana, you got the gorilla holding the banana AND the entire jungle.
Finished this lesson?