ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Composition
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 7.3

Composition

HAS-A relationships, delegation and composition over inheritance

12 min readStage 1 · Foundations14 interview questions
Prerequisites
6.4 Inheritance Design · 7.1 Interfaces
Covers
HAS-A relationship · Delegation · Composition over inheritance
Related
7.4 Interface-Based Design · Book 5 Vol III–IV (Decorator, Strategy, Composite, Adapter)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Composition builds an object from other objects that it holds as fields and uses to do its work. The relationship is has-a (a Car has an Engine) or uses-a, rather than is-a. The containing object exposes its own API and implements it by delegating to its parts.

A Car composed of collaborators, each behind an interface
Figure 1 — A Car composed of collaborators, each behind an interface

2Why It Exists

Composition reuses behaviour without the tight coupling of inheritance (6.4). The composed object depends only on its collaborators' public contracts, exposes only the operations it chooses, and can receive different collaborators — a different engine, a test fake, a decorated version — without any change to its code. It also avoids the combinatorial explosion of subclasses when behaviours must be combined.

Subclasses multiply with each combination; composed parts simply add up
Figure 2 — Subclasses multiply with each combination; composed parts simply add up

3Core Concepts

HAS-A relationship

A has-a relationship is modelled by a field. UML distinguishes two strengths: composition, where the part's lifecycle is owned by the whole (an Order's lines are created and discarded with the Order), and aggregation, where the part exists independently and may be shared (an Order refers to a Customer). In Java both are fields; the difference lies in who creates the part, whether it is shared, and whether it is exposed.

AspectComposition (strong)Aggregation / association (weak)
LifecyclePart created and discarded with the wholePart exists independently
SharingNot sharedMay be shared by many owners
Typical creationInside the ownerPassed in (injected)
ExampleOrder → OrderLineOrder → Customer; Service → Repository

Delegation

Delegation means the composed object forwards a request to a collaborator, possibly adding work before or after. It is how composition turns held objects into behaviour. Many design patterns are structured delegation: Decorator adds behaviour around a delegate of the same interface, Adapter translates to a delegate with a different interface, Proxy controls access to a delegate, and Strategy delegates a varying algorithm.

Car.start() delegates to its Engine
Figure 3 — Car.start() delegates to its Engine

Composition over inheritance

The guideline does not ban inheritance; it sets composition as the default. Use inheritance only for genuine behavioural subtypes designed for extension; use composition for reuse, variation and combination. In practice, a composed design usually pairs an interface for the role with small implementations and an object that holds the ones it needs.

4How It Works Internally

Composition needs no special support from the JVM: a has-a relationship is a reference field, and delegation is an ordinary method call through it. A Car holds references to its engine, its navigation and its list of wheels; the parts are separate objects on the heap. The garbage collector reclaims an owned part when the last reference to it, normally the owner's field, disappears, while a shared part stays alive as long as any owner still refers to it.

Delegation costs one extra call per layer, and in practice not even that. A call such as engine.start() through a field that always holds the same class is monomorphic, so the JIT inlines PetrolEngine.start() into Car.start(); a decorator chain built once at startup is usually inlined the same way. What remains is one small object per wrapper and one stack frame per layer in exception stack traces.

Frameworks generate delegation code. java.lang.reflect.Proxy creates, at run time, a class that implements given interfaces and forwards every call to an InvocationHandler (section 5). Spring uses such JDK proxies for beans used through an interface, and generated subclasses (CGLIB) otherwise; either way the caller holds the proxy and the proxy holds the real bean, as in Figure 4.

One call through a chain of decorators; the order of the layers is part of the behaviour
Figure 4 — One call through a chain of decorators; the order of the layers is part of the behaviour

5APIs / Features / Syntax

Java has no keyword for composition. It is built from a few language features, and the JDK itself is full of composed types. The table lists the building blocks and where the JDK uses each form.

Feature or APIUse in composition
private final fields set in the constructorMandatory collaborators, injected once; the object is complete after construction
Interfaces as field typesCollaborators can be replaced by other implementations, decorators or test doubles
Objects.requireNonNull(engine)Fails fast in the constructor when a collaborator is missing
RecordsImmutable values composed of other values: record Route(Location to, int km)
new BufferedReader(new InputStreamReader(in, UTF_8))Decorators in java.io: each layer adds decoding or buffering
Collections.unmodifiableList(list)A wrapper that restricts access to the list it holds
java.lang.reflect.ProxyGenerates a delegating class at run time, for any interface
JAVALoggingProxy.java
import java.lang.reflect.Proxy;
import java.util.Arrays;
 
public class LoggingProxy {
 
    interface PriceLookup { long price(String sku); }
 
    @SuppressWarnings("unchecked")
    static <T> T logged(Class<T> role, T target) {
        return (T) Proxy.newProxyInstance(role.getClassLoader(),
                new Class<?>[] { role },
                (proxy, method, args) -> {
                    System.out.println("-> " + method.getName()
                            + Arrays.toString(args));
                    Object result = method.invoke(target, args);
                    System.out.println("<- " + result);
                    return result;
                });
    }
 
    public static void main(String[] args) {
        PriceLookup real = sku -> sku.length() * 100L;
        PriceLookup lookup = logged(PriceLookup.class, real);
        long total = lookup.price("SKU-42") + lookup.price("PEN");
        boolean generated = Proxy.isProxyClass(lookup.getClass());
        System.out.println("total " + total + ", proxy: " + generated);
    }
}
OUTPUT
-> price[SKU-42]
<- 600
-> price[PEN]
<- 300
total 900, proxy: true

logged works for any interface: the generated class implements PriceLookup, and each call arrives at the handler as a Method plus arguments, which the handler logs and forwards to the real object with method.invoke. Spring's transaction and caching proxies have exactly this structure, with a transaction or a cache lookup where this one prints.

6Practical Examples

Example 1 — A car assembled from collaborators

Problem. Model a car whose engine and navigation can vary, without a subclass for each combination (Figure 2).

JAVAComposition and delegation
public interface Engine { void start(); }
public interface Navigation { Route route(Location to); }

public final class Car {
    private final Engine engine;  // has-a (injected: aggregation)
    private final Navigation navigation;
    private final List<Wheel> wheels;            // has-a (owned: composition)

    public Car(Engine engine, Navigation navigation) {
        this.engine = engine;
        this.navigation = navigation;
        this.wheels = List.of(new Wheel(), new Wheel(), new Wheel(), new Wheel());
    }

    public void start() { engine.start(); }                        // delegation
    public Route driveTo(Location to) { return navigation.route(to); }
}

Car petrol   = new Car(new PetrolEngine(), new GpsNavigation());
// no subclass
Car electric = new Car(new ElectricEngine(), new GpsNavigation());

Why it works. Car holds its parts as fields and implements start and driveTo by delegating. The engine and navigation are passed in, so the same class makes a petrol or an electric car; the wheels are created inside, so they live and die with the car.

Example 2 — Mini program: a notifier assembled from parts

Problem. A service must send an SMS when an order ships. The SMS gateway sometimes times out, and operations want a count of sent and failed messages. Neither retries nor counting belong in the notifier, and neither should need a subclass of the SMS client.

JAVANotifications.java
import java.util.function.Function;
 
public class Notifications {
 
    interface Channel { void send(String to, String text); }
 
    static final class FlakySms implements Channel {    // fails twice
        private int calls;
        public void send(String to, String text) {
            if (++calls <= 2) throw new IllegalStateException("timeout");
            System.out.println("  SMS to " + to + ": " + text);
        }
    }
 
    static final class Retrying implements Channel {        // decorator 1
        private final Channel delegate;
        private final int attempts;
        Retrying(Channel delegate, int attempts) {
            if (attempts < 1) throw new IllegalArgumentException("< 1");
            this.delegate = delegate;
            this.attempts = attempts;
        }
        public void send(String to, String text) {
            for (int i = 1; ; i++) {
                try { delegate.send(to, text); return; }
                catch (IllegalStateException e) {
                    System.out.println("  attempt " + i + " failed: "
                            + e.getMessage());
                    if (i == attempts) throw e;
                }
            }
        }
    }
 
    static final class Counting implements Channel {        // decorator 2
        private final Channel delegate;
        int sent, failed;
        Counting(Channel delegate) { this.delegate = delegate; }
        public void send(String to, String text) {
            try { delegate.send(to, text); sent++; }
            catch (RuntimeException e) { failed++; throw e; }
        }
    }
 
    static final class OrderNotifier {                // the composed object
        private final Channel channel;
        private final Function<String, String> template;
        OrderNotifier(Channel channel, Function<String, String> template) {
            this.channel = channel;
            this.template = template;
        }
        void shipped(String phone, String orderId) {
            channel.send(phone, template.apply(orderId));
        }
    }
 
    public static void main(String[] args) {             // composition root
        Counting counting = new Counting(new Retrying(new FlakySms(), 3));
        OrderNotifier notifier =
                new OrderNotifier(counting, id -> "order " + id + " shipped");
        notifier.shipped("+91-90000-00001", "A-1001");
        notifier.shipped("+91-90000-00002", "A-1002");
        System.out.println("sent=" + counting.sent
                + " failed=" + counting.failed);
    }
}
OUTPUT
  attempt 1 failed: timeout
  attempt 2 failed: timeout
  SMS to +91-90000-00001: order A-1001 shipped
  SMS to +91-90000-00002: order A-1002 shipped
sent=2 failed=0

Why it behaves this way. All four objects implement or use Channel, so main can stack them: Counting wraps Retrying, which wraps the real channel (Figure 4). The first message fails twice inside Retrying and succeeds on the third attempt; Counting sees only the final result, so it reports two messages sent and none failed. The template is composed in as well, as a Function, so the wording can change without touching the notifier. Swapping the two decorators would make Counting see every attempt and report two failures.

Example 3 — Adding retries by wrapping, not subclassing

Problem. Add retries to any payment gateway, from any provider, without changing it.

JAVAAdding behaviour by wrapping, not subclassing
public final class RetryingGateway implements PaymentGateway {    // Decorator
    private final PaymentGateway delegate;
    private final int attempts;

    public RetryingGateway(PaymentGateway delegate, int attempts) {
        if (attempts < 1) throw new IllegalArgumentException("attempts < 1");
        this.delegate = delegate;
        this.attempts = attempts;
    }

    @Override
    public Receipt charge(Money amount, Card card) {
        for (int i = 1; ; i++) {
            try {
                return delegate.charge(amount, card);
            } catch (TransientPaymentException e) {
                if (i == attempts) throw e;
            }
        }
    }
}

PaymentGateway gateway = new RetryingGateway(new CardGateway(key), 3);

Why it works. RetryingGateway is a Decorator: it implements the same interface as the object it wraps, so callers cannot tell the difference. It catches only TransientPaymentException and gives up after the last attempt by rethrowing it. The check in the constructor matters: with attempts 0, i == attempts would never be true and the loop would retry for ever.

Example 4 — The fragile base class, and the composed fix

Problem. Count how many elements were ever added to a set. The tempting solution extends HashSet and overrides add and addAll.

JAVAFragileBase.java
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public class FragileBase {
 
    static class CountingSet<E> extends HashSet<E> {  // reuse by inheritance
        private static final long serialVersionUID = 1L;
        int added;
        @Override public boolean add(E e) { added++; return super.add(e); }
        @Override public boolean addAll(Collection<? extends E> c) {
            added += c.size();
            return super.addAll(c);                     // calls add() again
        }
    }
 
    static final class CountedSet<E> {               // reuse by composition
        private final Set<E> items = new HashSet<>();
        private int added;
        boolean add(E e) { added++; return items.add(e); }
        boolean addAll(Collection<? extends E> c) {
            added += c.size();
            return items.addAll(c);                   // HashSet's own add()
        }
        int added() { return added; }
        int size() { return items.size(); }
    }
 
    public static void main(String[] args) {
        List<String> three = List.of("pen", "ink", "pad");
        CountingSet<String> inherited = new CountingSet<>();
        inherited.addAll(three);
        CountedSet<String> composed = new CountedSet<>();
        composed.addAll(three);
        System.out.println("inherited: size " + inherited.size()
                + ", counted " + inherited.added);
        System.out.println("composed:  size " + composed.size()
                + ", counted " + composed.added());
    }
}
OUTPUT
inherited: size 3, counted 6
composed:  size 3, counted 3

Why it behaves this way. HashSet.addAll is inherited from AbstractCollection, which implements it by calling add for each element. The subclass counts three in addAll and then three more in its own add, so it reports six. Nothing in HashSet's public API promises or forbids this self-use; it could change in any release, which is what makes the base class fragile. The composed version holds a HashSet and calls it, so the set's internal calls never reach the counting code.

Example 5 — Who closes what: composition and aggregation

Problem. A report job writes into a buffer it creates and borrows connections from a pool that many jobs share. The section 3 table says who owns each part; this program shows what goes wrong when an object closes a part it does not own.

JAVALifecycles.java
import java.io.StringWriter;
 
public class Lifecycles {
 
    static final class Pool implements AutoCloseable {  // shared by many jobs
        boolean open = true;
        String borrow() {
            if (!open) throw new IllegalStateException("pool is closed");
            return "conn";
        }
        @Override public void close() { open = false; }
    }
 
    static class ReportJob implements AutoCloseable {
        protected final Pool pool;                            // aggregation
        private final StringWriter out = new StringWriter();  // composition
        ReportJob(Pool pool) { this.pool = pool; }
        void run(String row) { pool.borrow(); out.write(row); }
        @Override public void close() {          // closes only what it owns
            int chars = out.toString().length();
            System.out.println("  job done, " + chars + " chars");
        }
    }
 
    static final class GreedyJob extends ReportJob {
        GreedyJob(Pool pool) { super(pool); }
        @Override public void close() {
            super.close();
            pool.close();                         // the bug
        }
    }
 
    static void nightly(Pool pool, boolean greedy) {
        for (String row : new String[] { "north,120\n", "south,95\n" }) {
            ReportJob job = greedy ? new GreedyJob(pool)
                                   : new ReportJob(pool);
            try (job) {
                job.run(row);
            } catch (IllegalStateException e) {
                System.out.println("  failed: " + e.getMessage());
            }
        }
    }
 
    public static void main(String[] args) {
        try (Pool pool = new Pool()) {
            System.out.println("jobs that close only their own parts:");
            nightly(pool, false);
            System.out.println("jobs that also close the shared pool:");
            nightly(pool, true);
        }
    }
}
OUTPUT
jobs that close only their own parts:
  job done, 10 chars
  job done, 9 chars
jobs that also close the shared pool:
  job done, 10 chars
  job done, 0 chars
  failed: pool is closed

Why it behaves this way. The buffer is composition: the job creates it, nobody else sees it, and its lifetime ends with the job. The pool is aggregation: it is injected and shared, so its lifetime belongs to the code that created it, here main. GreedyJob closes the pool in its own close, so the next job fails at borrow; try-with-resources still closes that second job, which reports 0 characters. In a real service the "next job" is every other request in the process.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Exposing collaborators through getters, so callers write car.getEngine().start()Breaks the Law of Demeter: callers depend on internals, and replacing the engine breaks themOffer the operation on the owner (car.start()) and keep the part private
Creating collaborators with new inside the class when they should be injectedThe class cannot be configured or tested with another implementation; composition loses its flexibilityInject them through the constructor; create only owned parts inside
Forwarding classes that must implement very large interfacesDozens of one-line forwarding methods, and a method added later is easily forgottenKeep interfaces small, or write one abstract forwarding base and extend it
Deep chains of wrappers that are hard to debugStack traces show many layers, and it is unclear which layer changed the behaviourKeep layers few and named, and build the chain in one place (Figure 4)
Extending a concrete class only to reuse its codeThe subclass depends on how the parent calls its own methods (Example 4)Hold an instance and delegate; expose only the operations you need
Decorators in the wrong orderMetrics count calls instead of attempts, or a retry keeps hitting an open circuitDecide the order at the composition root and test it
An owner that closes a shared, injected partEvery other user of the part fails afterwards (Example 5)Close only what you created; the creator of a shared part closes it

8Performance & Production Considerations

  • Composition costs one object per part and per wrapper, which is negligible next to the work most services do. Build decorator chains once at startup, not per request.
  • The order of decorators is behaviour. With breaker(retry(client)) the circuit breaker counts one failure per exhausted retry; with retry(breaker(client)) it counts every attempt, opens sooner, and the retry then fails fast against the open circuit. Write the order down at the composition root and test it.
  • Framework proxies apply only to calls that pass through the proxy. A method that calls another method of the same Spring bean through this bypasses it, so @Transactional or @Cacheable on the second method has no effect (Q11).
  • Name decorators for what they add (RetryingGateway, MeteredGateway) and give them a toString that shows the chain, so logs and stack traces reveal the composition.

9Architecture & Design Considerations

Composition is how applications are assembled at every level: objects from collaborators, services from repositories and clients, systems from services. Dependency injection containers are, in effect, composition engines. Cross-cutting concerns — retries, caching, metrics, transactions — are best added by composition (decorators, proxies, AOP) rather than base classes, which is exactly how Spring implements @Transactional and @Cacheable.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is composition?

Building an object from other objects held as fields and implementing its behaviour by using them — a has-a relationship rather than is-a. A Car that holds an Engine and calls engine.start() from its own start() is the standard example; the engine can be replaced without changing Car.

Q2L2 · IntermediateConcept

What is delegation?

Forwarding a request from one object to a collaborator that does the work, possibly with added logic before or after. It is the mechanism by which composition reuses behaviour.

Q3L2 · IntermediateConcept

What is the difference between composition and aggregation?

In composition the whole owns the part's lifecycle and the part is not shared (an order's lines). In aggregation the part exists independently and may be shared (an order's customer). Both are fields in Java; the difference is ownership and creation.

Q4L3 · Senior EngineerTrade-off

Why is composition preferred over inheritance?

It couples only to public contracts, exposes only chosen operations, allows collaborators to vary at run time and in tests, avoids fragile base classes, and combines behaviours without subclass explosion.

Q5L3 · Senior EngineerDesign

How would you add retry and metrics to a payment client without modifying it or subclassing it?

Wrap it in decorators that implement the same interface: a retrying decorator and a metrics decorator, each delegating to the next. Compose them at wiring time. The client and callers are unchanged. The same chain can be reordered or extended later, for example with a circuit breaker, without touching the client.

Q6L4 · Technical ArchitectInternals

How do frameworks like Spring use composition for cross-cutting concerns?

They create proxies around beans — composition by delegation — that add transactions, caching, security or metrics before and after delegating to the real bean. The bean class is not subclassed by user code, and concerns can be combined through configuration.

Q7L1 · BasicConcept

What is the Law of Demeter, and how does it relate to composition?

An object should call methods only on itself, its fields, its parameters and objects it creates, not on objects returned by them ("talk only to your friends"). car.start() follows it; car.getEngine().start() does not, because the caller now depends on the car's parts. Composition works best when the owner offers operations and keeps its parts private.

Q8L2 · IntermediateCode

What does this program print?

JAVAForwardQuiz.java
public class ForwardQuiz {
    interface Greeter {
        String greet();
        default String twice() { return greet() + greet(); }
    }
    static class Plain implements Greeter {
        public String greet() { return "hi"; }
    }
 
    static class Loud implements Greeter {              // composition
        private final Greeter inner;
        Loud(Greeter inner) { this.inner = inner; }
        public String greet() { return inner.greet().toUpperCase(); }
        public String twice() { return inner.twice(); } // forwarded
    }
    static class Shout extends Plain {                  // inheritance
        public String greet() { return super.greet().toUpperCase(); }
    }
 
    public static void main(String[] args) {
        System.out.println(new Loud(new Plain()).twice());
        System.out.println(new Shout().twice());
    }
}

It prints hihi and then HIHI. Loud forwards twice() to the wrapped Plain, whose default twice() calls greet() on this, which is the Plain object, so the upper-casing in Loud.greet is bypassed. Shout inherits twice(), and greet() inside it is dispatched to Shout.greet. A wrapper changes only the calls that go through it; the wrapped object's calls to itself never reach the wrapper.

Q9L3 · Senior EngineerTricky

A client fails twice and then succeeds. What do the call counters report with metrics(retry(client)) and with retry(metrics(client))?

With metrics outside, the counter sees one call that succeeded, because the retries happen inside it. With metrics inside, it sees three calls: two failures and one success. Both are correct, but they answer different questions, "how often did callers succeed" and "how healthy is the dependency", so many teams measure at both levels (Example 2).

Q10L3 · Senior EngineerInternals

How do JDK dynamic proxies implement delegation, and when does Spring use a generated subclass instead?

Proxy.newProxyInstance generates a class at run time that implements the given interfaces; each method call is passed to an InvocationHandler with the Method and arguments, and the handler usually calls the real object (section 5). It works only for interfaces. Spring uses it when a bean is used through an interface and proxying of the target class is not forced; otherwise it generates a subclass of the bean class with CGLIB, which cannot proxy final classes or final methods.

Q11L3 · Senior EngineerScenario

A service method calls another method of the same bean that is annotated @Transactional(propagation = REQUIRES_NEW). Logs show no new transaction, and a failure rolls back everything. Why, and how do you fix it?

The transaction is applied by a proxy that wraps the bean, and the inner call goes through this, not through the proxy, so the annotation is never seen. Move the inner method to another bean and inject it, which makes the call pass through that bean's proxy, or use a TransactionTemplate explicitly. Self-injection or AopContext.currentProxy() also work but hide the dependency.

Q12L3 · Senior EngineerTricky

A decorated object registers this as a listener with an event bus. Why do events bypass the decorator?

The wrapped object does not know it is wrapped, so this is the inner object, and the bus calls it directly. This is the "self problem" of composition (Q8 shows the same effect for a self-call). Register the outermost object from the composition root instead, or pass the wrapper into the inner object explicitly when such callbacks are part of its design.

Q13L4 · Technical ArchitectTrade-off

When is inheritance still the right choice instead of composition?

When the subtype really is a behavioural subtype of a class designed and documented for extension, such as a framework's abstract base whose hook methods are specified, or a sealed hierarchy you own completely. Inheritance then removes forwarding code and keeps the variants in one place. Composition costs more objects and forwarding, but couples only to the public contract, so prefer it for reuse across boundaries and for behaviour that must vary at run time.

Q14L5 · Solution ArchitectDesign

Thirty services call external providers through client libraries. How do you add retries, timeouts, circuit breakers and metrics consistently across the organisation?

Standardise the composition, not the clients. Each client implements a small interface; a shared library provides decorators for timeout, retry, circuit breaker and metrics with one documented order, built by a factory or a framework integration such as Resilience4j with Spring. Defaults come from central configuration and can be tuned per dependency, dashboards use the same metric names everywhere, and an architecture test fails any build that calls a raw provider client outside the factory.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Composition = has-a; behaviour comes from delegating to held collaborators.
  • Composition owns part lifecycles; aggregation references independent parts.
  • Decorator, Adapter, Proxy and Strategy are structured delegation.
  • Default to composition; reserve inheritance for true subtypes.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.