1. Concept library
  2. Java & Spring Boot
  3. Module 2: Object-oriented design

Concept

Composition

Build classes out of other objects they hold and delegate to, instead of extending them. Composition keeps each class focused and lets you swap parts, including in tests.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain how delegation differs from extending a class
  2. Build a class from objects it holds and delegates to
  3. Spot the class that extends HashMap to borrow one method

In practice

A few lines that show Composition doing its job.

Java
public class OrderService {
    private final OrderRepository orders;
    private final PaymentGateway payments;
    private final Clock clock;

    public OrderService(OrderRepository orders, PaymentGateway payments, Clock clock) {
        this.orders = orders; this.payments = payments; this.clock = clock;
    }

    public Receipt place(Order order) {
        var charge = payments.charge(order.total());
        return orders.save(order.paidAt(clock.instant(), charge));
    }
}

The common mistake

Watch for

Extending a class to borrow one method, such as class UserCache extends HashMap. Every HashMap method becomes part of your API, and a change in the parent can break you.

What to know first

Your roadmap puts these before Composition, unless you already know them.

How it stays learned

Once a session shows you understand Composition, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Composition.

Previous in the module← Encapsulation