In this tutorial
Sooner or later every Java developer faces this design question: should Car extend Engine, or should a Car have an Engine? The answer shapes how easy your code is to change for years.
This tutorial explains inheritance and composition with working examples, shows where inheritance goes wrong, and gives you a simple rule for choosing.
Inheritance: the “is-a” relationship
Inheritance lets a class reuse and specialise another class. The child class (subclass) gets all the accessible fields and methods of the parent (superclass), and can add or override behaviour.
public class Animal {
protected final String name;
public Animal(String name) {
this.name = name;
}
public String sound() {
return "...";
}
public String describe() {
return name + " says " + sound();
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // call the parent constructor
}
@Override
public String sound() {
return "Woof";
}
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public String sound() {
return "Meow";
}
}
Animal[] pets = { new Dog("Bingo"), new Cat("Tom") };
for (Animal pet : pets) {
System.out.println(pet.describe());
}
// Bingo says Woof
// Tom says Meow
Key points:
extendscreates the relationship. Java allows only one superclass per class.super(...)calls the parent’s constructor and must be the first statement.@Overrideasks the compiler to check that you really are overriding a parent method. Always use it.- A
Dogcan be used anywhere anAnimalis expected. That is polymorphism, and it is the main benefit of inheritance.
Inheritance is the right tool when the relationship is a genuine, permanent “is-a”: a Dog is an Animal, a SavingsAccount is a BankAccount.
Composition: the “has-a” relationship
Composition builds a class by holding references to other objects and delegating work to them:
public class Engine {
private final int horsepower;
public Engine(int horsepower) {
this.horsepower = horsepower;
}
public String start() {
return "Engine with " + horsepower + "hp started";
}
}
public class Car {
private final String model;
private final Engine engine; // Car HAS an Engine
public Car(String model, Engine engine) {
this.model = model;
this.engine = engine;
}
public String drive() {
return model + ": " + engine.start();
}
}
Car corolla = new Car("Corolla", new Engine(132));
System.out.println(corolla.drive()); // Corolla: Engine with 132hp started
A car is not an engine, so inheritance would be wrong here. Composition models the real relationship and keeps the two classes independent.
Where inheritance goes wrong
Inheritance couples the child tightly to the parent’s implementation, not just its public API. Here is the classic example (adapted from Joshua Bloch’s Effective Java). We want a set that counts how many items have ever been added:
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class CountingSet<E> extends HashSet<E> {
private int addCount = 0;
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
public static void main(String[] args) {
CountingSet<String> set = new CountingSet<>();
set.addAll(List.of("a", "b", "c"));
System.out.println(set.getAddCount()); // 6, not 3!
}
}
Why 6? Internally, HashSet.addAll calls add for each element, so every item is counted twice. Our subclass broke because of a hidden detail of the parent’s implementation, and a future JDK version could change that detail again. This is called the fragile base class problem.
The composition fix
Wrap the set instead of extending it, and forward calls to it:
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CountingSetWrapper<E> {
private final Set<E> inner = new HashSet<>();
private int addCount = 0;
public boolean add(E e) {
addCount++;
return inner.add(e);
}
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return inner.addAll(c); // inner calls ITS OWN add, not ours
}
public int getAddCount() {
return addCount;
}
public int size() {
return inner.size();
}
public static void main(String[] args) {
CountingSetWrapper<String> set = new CountingSetWrapper<>();
set.addAll(List.of("a", "b", "c"));
System.out.println(set.getAddCount()); // 3
}
}
The wrapper does not care how HashSet works internally. It only uses its public methods. You can even swap HashSet for TreeSet without breaking anything.
Composition and interfaces: flexibility at runtime
Composition really shines when combined with interfaces. You can change behaviour by plugging in a different object:
interface PaymentMethod {
String pay(double amount);
}
class CardPayment implements PaymentMethod {
public String pay(double amount) { return "Paid NGN " + amount + " by card"; }
}
class TransferPayment implements PaymentMethod {
public String pay(double amount) { return "Paid NGN " + amount + " by bank transfer"; }
}
class Checkout {
private PaymentMethod method;
Checkout(PaymentMethod method) { this.method = method; }
void setMethod(PaymentMethod method) { this.method = method; }
String complete(double total) { return method.pay(total); }
}
With inheritance you would need CardCheckout, TransferCheckout, UssdCheckout and so on, and you could not switch method at runtime. With composition, one Checkout class works with any payment method, including ones that do not exist yet. This is the idea behind the Strategy pattern and dependency injection in Spring.
How to choose
Ask these questions:
- Is it truly “is-a” for the object’s whole life? A
Manageris anEmployee, but a manager might stop being a manager. That role is better modelled as something an employee has. - Would every method of the parent make sense on the child? If you find yourself overriding methods to throw
UnsupportedOperationException, inheritance is wrong. - Do you control both classes? Extending classes from other libraries is risky, because their internals can change.
The widely quoted guideline from the Design Patterns book is: favour composition over inheritance. That does not mean “never inherit”. It means composition is the safer default, and inheritance should be a deliberate choice for genuine type hierarchies.
Quick comparison
- Relationship: inheritance is “is-a”; composition is “has-a”.
- Coupling: inheritance couples you to the parent’s implementation; composition only to a public API.
- Flexibility: inheritance is fixed at compile time; composition can swap parts at runtime.
- Reuse: inheritance reuses code automatically; composition needs simple forwarding methods.
- Polymorphism: inheritance gives it directly; composition gets it through interfaces.
Summary
- Use inheritance for real, stable “is-a” relationships, ideally within code you own.
- Use composition for “has-a” relationships and whenever you want to swap behaviour.
- Inheritance can break when the parent’s internals change: the fragile base class problem.
- Combine composition with interfaces for flexible, testable designs.
Next: understand the other half of the picture with interfaces vs abstract classes.