Composition

A class is built from other objects as often as it inherits from a class. A car has an engine, a report has a builder, a library has a shelf. The relation is called composition, and the method that passes the work to the object is called delegation.

has-a

Composition is a field whose type is another class. The car below keeps an Engine in a final field, and the engine is passed to the constructor, so the car never creates one and never depends on how it is built.

The file Car.java:

public class Car { private final String name; private final Engine engine; Car(String name, Engine engine) { this.name = name; this.engine = engine; } void start() { System.out.print(name + ": "); engine.start(); } Engine engine() { return engine; } public static void main(String[] args) { Car car = new Car("sedan", new Engine(4)); car.start(); System.out.println("cylinders: " + car.engine().cylinders()); } } class Engine { private final int cylinders; Engine(int cylinders) { this.cylinders = cylinders; } void start() { System.out.println("engine starts, " + cylinders + " cylinders"); } int cylinders() { return cylinders; } }

javac -Xlint:all Car.java
java Car

sedan: engine starts, 4 cylinders
cylinders: 4

start writes the name and then calls the engine, which writes the rest of the line. The car did not copy the engine logic; it used the engine object, and a different engine would change the sound without a change to Car.

Delegation

engine.start() is delegation: the method of the outer object passes the work to a method of the object it holds. The outer object decides when and in which order, and the inner one does its own job. A delegation chain of two or three objects is ordinary; a chain of ten is a design smell.

Delegation is also the way a class uses a library object without exposing it: the report below keeps a private builder, adds a line through its own method and returns the text through toString. A caller never sees the StringBuilder.

Composition against inheritance

Inheritance says is-a and composition says has-a. A car is not an engine, so extends Engine would be wrong even though it would compile. A class that inherits gets every method of its superclass and depends on how the superclass implements them; a class that composes depends only on the methods it calls.

The rule of thumb is to compose first and inherit when the type really is a subtype. The inheritance part begins with lesson 048 and shows the cases where the subtype relation is real.

A class built from a builder

public class Report { private final StringBuilder builder = new StringBuilder(); Report add(String line) { builder.append(line).append('\n'); return this; } @Override public String toString() { return builder.toString(); } public static void main(String[] args) { Report report = new Report().add("one").add("two"); System.out.print(report); } }

javac -Xlint:all Report.java
java Report

one
two

append returns the builder itself, so builder.append(line).append('\n') is a chain of two calls on one object. The report returns this from its own add, so the chain continues at the level of the report. Delegation and the fluent style are the same idea at two levels.

Exercises

  1. Give stop() method and let Report keep its own

    Questions

    A new set of questions in a new order every time. Choose one answer for each, then check.

    1. What is composition?

      Answer

      A field that holds another object and uses its methods

      The outer object has the inner one as a field, which is the has-a relation.

    2. What is delegation?

      Answer

      A method that passes its work to a method of another object

      The delegating method decides and the delegate does the work it owns.

    3. Which relation does class Car extends Engine claim?

      Answer

      A car is an engine

      Inheritance is the is-a relation, and a car is not a kind of engine.

    4. What does this program print? public class Q1 { public static void main(String[] args) { Engine engine = new Engine(6); Car car = new Car("coupe", engine); car.start(); } } class Car { private final String name; private final Engine engine; Car(String name, Engine engine) { this.name = name; this.engine = engine; } void start() { System.out.println(name + ": " + engine.cylinders() + " cylinders"); } } class Engine { private final int cylinders; Engine(int cylinders) { this.cylinders = cylinders; } int cylinders() { return cylinders; } }

      Answer

      coupe: 6 cylinders

      The car reads the cylinder count through the engine it holds.

    5. What does this program print? public class Q2 { public static void main(String[] args) { Report report = new Report(); report.add("a"); report.add("b"); System.out.print(report); } } class Report { private final StringBuilder builder = new StringBuilder(); void add(String line) { builder.append(line).append('\n'); } @Override public String toString() { return builder.toString(); } }

      Answer

      a / b

      Each add appends the line and a newline, and the print writes both lines.

    6. What does this program print? public class Q3 { public static void main(String[] args) { Report report = new Report().add("x").add("y"); System.out.print(report); } } class Report { private final StringBuilder builder = new StringBuilder(); Report add(String line) { builder.append(line).append('\n'); return this; } @Override public String toString() { return builder.toString(); } }

      Answer

      x / y

      add returns the report, so the second call appends after the first.

    7. What does this program print? public class Q4 { public static void main(String[] args) { Car car = new Car(new Engine()); System.out.println(car.engine == null); } } class Car { final Engine engine; Car(Engine engine) { this.engine = engine; } } class Engine { }

      Answer

      false

      The constructor stored a new engine, so the field is not null.

    8. Why is composition less fragile than inheritance?

      Answer

      The class depends only on the methods it calls

      An inheritance hierarchy ties the subclass to the superclass implementation; composition depends on a small interface.

    9. What does a constructor that takes the inner object, rather than creating it, allow?

      Answer

      A different implementation of the same type

      The caller chooses the object, so a test or another engine can be passed in.

    10. What does this program print? public class Q5 { public static void main(String[] args) { Engine e = new Engine(2); System.out.println(e.cylinders()); } } class Engine { private final int cylinders; Engine(int cylinders) { this.cylinders = cylinders; } int cylinders() { return cylinders; } }

      Answer

      2

      The constructor stored 2 and the getter returns it.

    The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

    Article author: Arthur Isaev