Composition and dependencies
What you will learn
Composition builds an object using other objects instead of extending their classes. A dependency is another object or service required to perform a task. Passing a dependency to a constructor makes it explicit: a delivery calculator can delegate price calculation to a Rate object.
After this lesson you can:
- Identify the collaborator in an object relationship.
- Use constructor injection and distinguish shared from independent collaborators.
Use a separate Main.java for each example. Compile with javac Main.java and run with java Main. The code is compatible with Java 21; Java 25 execution is not yet verified.
class Rate { private final int centsPerItem; Rate(int centsPerItem) { if (centsPerItem < 0 || centsPerItem > 1000) throw new IllegalArgumentException("rate outside range"); this.centsPerItem = centsPerItem; } public int cost(int items) { if (items < 0 || items > 1000) throw new IllegalArgumentException("items outside range"); return centsPerItem * items; }}class Delivery { private final Rate rate; Delivery(Rate rate) { if (rate == null) throw new IllegalArgumentException("missing rate"); this.rate = rate; } public int quote(int items) { return rate.cost(items); }}public class Main { public static void main(String[] args) { Delivery local = new Delivery(new Rate(40)); Delivery distant = new Delivery(new Rate(65)); System.out.println(local.quote(3)); System.out.println(distant.quote(3)); }}Expected output:
120195Two instances use different rates without changing Delivery.
Has-a relationships and delegation
Delivery stores a Rate reference and forwards quote to rate.cost. This is a has-a relationship: Delivery has a rate, not a kind of rate. Delegation means asking that collaborator to perform part of the work. The constructor accepts a rate that has already been created; this is a simple form of dependency injection, with no framework required. Each rate in the example is immutable because its only field is a private final primitive. Price and item limits keep the integer calculation bounded. Prices are illustrative integer cents, not a complete payment model.
A class diagram describes types: Delivery → Rate. A runtime object diagram describes actual instances: deliveryA → rateA and deliveryB → rateB. The arrows mean references. Two deliveries may also point to the same rate. Composition in informal Java design includes such reference-based collaboration; stricter modeling terminology distinguishes ownership (composition) from shared aggregation. A Java field does not enforce exclusive ownership or automatic resource cleanup. If a mutable collaborator is shared, both callers can observe its changes. If independent state is needed, create independent collaborators.
Inheritance models an is-a relationship between types, while polymorphism lets callers work through a shared type with behavior determined by the actual object. Both receive detailed treatment in Chapter 11. Use composition here because a delivery calculation needs a rate, not because every inheritance relationship is wrong.
class Counter { private int count; public void increment() { count++; } public int count() { return count; }}class Desk { private final Counter counter; Desk(Counter counter) { this.counter = counter; } public void serve() { counter.increment(); } public int served() { return counter.count(); }}public class Main { public static void main(String[] args) { Counter counter = new Counter(); Desk a = new Desk(counter); Desk b = new Desk(counter); a.serve(); System.out.println(a.served()); System.out.println(b.served()); }}Expected output:
11Both desks hold a reference to the same counter object.
Check a boundary or variation
class Counter { private int count; public void increment() { count++; } public int count() { return count; }}class Desk { private final Counter counter; Desk(Counter counter) { this.counter = counter; } public void serve() { counter.increment(); } public int served() { return counter.count(); }}public class Main { public static void main(String[] args) { Desk a = new Desk(new Counter()); Desk b = new Desk(new Counter()); a.serve(); System.out.println(a.served()); System.out.println(b.served()); }}Expected output:
10Separate objects have independent counts.
Common mistakes
A final dependency field prevents reassignment of the field, not mutation of the referenced object. Also, a constructor argument is not automatically non-null: check required dependencies at construction. The Counter/Desk example uses only trusted non-null counters and a small bounded number of increments.
Practice
Create a Rate with a bounded nonnegative cents-per-item value and a Delivery that accepts a Rate through its constructor. Delegate the quote operation. Verify zero items, different rates and the highest accepted values.
Store the Rate as a private final field. Do not duplicate cost arithmetic inside Delivery.
Next: Abstraction and public contracts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Composition and dependencies — knowledge check
Apply the stated Java 21-compatible contracts and predict observable behavior.
Which relationship fits Delivery and Rate?
What does constructor injection do here?
Two desks share one Counter. A increments it. What does B observe?
How can two desks have separate counts?
What does private final Rate rate guarantee?