Skip to main content
OOP and design · Topic 6 of 12

Composition over inheritance

Definition​

Composition means building a class by holding other objects and using them, instead of extending a class. It keeps classes loosely coupled and easy to change, so it is usually preferred over inheritance when you only want to reuse behaviour.

Example code​

A notifier that can swap how it sends messages

interface Sender {
void send(String message);
}

class EmailSender implements Sender {
public void send(String message) { System.out.println("Email: " + message); }
}

class SmsSender implements Sender {
public void send(String message) { System.out.println("SMS: " + message); }
}

class OrderNotifier {
private final Sender sender; // "has a" sender, not "is a" sender

OrderNotifier(Sender sender) { this.sender = sender; }

void orderShipped(int orderId) { sender.send("Order " + orderId + " has shipped"); }
}

class Demo {
public static void main(String[] args) {
new OrderNotifier(new EmailSender()).orderShipped(101);
new OrderNotifier(new SmsSender()).orderShipped(102); // swapped without touching OrderNotifier
}
}

// Output:
// Email: Order 101 has shipped
// SMS: Order 102 has shipped

Finished this page? Track your progress (saved only in your browser).