Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 201 ยท Object-Oriented Programming

Composition, Aggregation and Association

Learn has-a relationships in Java - association, aggregation and composition, why to favor composition over inheritance, and how delegation keeps classes flexible.

Inheritance models an is-a relationship: a SavingsAccount is an Account. But most relationships in real programs are has-a: a car has an engine, an order has line items, a team has players. In Java you express has-a by giving one object a field that refers to another. That simple idea, objects built out of other objects, is called composition, and it's the main way professional Java code is put together.

This lesson names the three flavors of has-a (association, aggregation and composition), shows how they differ in code and in object lifetime, and explains the most repeated piece of design advice in object-oriented programming: favor composition over inheritance. You'll see a real bug that inheritance causes, the same feature rebuilt with composition, and how delegation lets you swap behavior at run time.

Three kinds of has-a

All three relationships look the same in code (a field holding a reference), but they mean different things about ownership and lifetime:

Relationship Meaning Lifetime Example
Association One object uses or knows about another. Independent. A Taxi knows its current Passenger.
Aggregation A whole contains parts, but the parts can exist and be shared on their own. Parts outlive the whole. A Team has Players; a player can move to another team.
Composition A whole owns its parts; the parts make sense only inside it. Parts live and die with the whole. An Order owns its OrderLines; a House owns its Rooms.

Aggregation and composition are both special kinds of association. Java has no keywords for them; the difference shows up in who creates the part, who else can reach it, and what happens when the whole goes away. In UML diagrams you'll see aggregation drawn with a hollow diamond and composition with a filled one.

Composition: the whole owns its parts

In composition, the whole creates its parts (or copies what it receives), keeps them private, and never hands out references that would let outsiders change them. When the whole is no longer reachable, its parts become garbage too.

Java An order that owns its lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

OrderLine is a private nested record: nobody outside Order can even name the type, let alone create a line for some other order. lineDescriptions() returns a new unmodifiable list (toList()), so callers can read but can't reach into the order's internal list. That's the encapsulation side of composition: the whole guards its parts.

Aggregation: parts with their own life

In aggregation the parts are created elsewhere and passed in. The whole keeps references to them, but doesn't own them: the same part can belong to several wholes, and it keeps existing after the whole is gone.

Java Players shared between teams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both teams show Inรฉs with 2 goals, because they share one Player object. Changes made through one team are visible through the other. That is exactly what you want for aggregation, and exactly what you don't want for composition. If Order stored a list handed to it by the caller without copying, the caller could later add or remove lines behind the order's back. When in doubt, copy what you receive and copy what you return (Copying Objects covers the techniques).

Association is the loosest form: an object holds or receives a reference to use it, with no sense of "part of". A Taxi with a currentPassenger field, or a method that takes a Printer parameter to print something, are associations.

Favor composition over inheritance

Inheritance is powerful, but it couples a subclass tightly to its parent's implementation, not just its public contract. If the parent's internal behavior changes, or was never documented, a correct-looking subclass can break. Here's a realistic example: a set that counts how many elements were ever added to it.

Java Inheritance breaks: counting additions twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The count is 6, not 3. HashSet.addAll happens to be implemented (in AbstractCollection) by calling add for each element, and add is overridden, so every element is counted twice. You could "fix" it by removing the addAll override, but then your class depends on an undocumented detail of HashSet that a future JDK could change. This fragility has a name: the fragile base class problem.

Composition avoids it. Instead of being a set, the class has a set and forwards calls to it. This is called delegation:

Java Composition fixes it: wrap and delegate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The count is now correct (4 additions, 3 stored elements), and the wrapper gained a bonus: it works with any Set, here a TreeSet, which inheritance from HashSet could never do. The cost is forwarding methods. A full version would implements Set<E> and forward every method; you can save effort by extending AbstractSet, a class designed for extension.

Why composition usually wins

  • Encapsulation. The wrapper depends only on the delegate's public contract, never on its internals.
  • Flexibility. The part can be swapped, even at run time, for another implementation of the same interface.
  • No accidental API. A subclass of HashSet inherits dozens of public methods, some of which might bypass your rules. A wrapper exposes only what you choose.
  • Multiple capabilities. A class can extend one class, but it can hold any number of parts.
  • Easier testing. You can pass a fake or simplified part in tests.

Delegation to swap behavior

The most common form of composition in modern Java is holding an interface-typed field and delegating a decision to it. Change the object in the field and the behavior changes, with no subclass in sight. This is the strategy pattern (Structural and Behavioral Design Patterns):

Java A checkout with a swappable pricing policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With inheritance you'd need RegularCheckout, PercentOffCheckout, FixedOffCheckout, and a new subclass for every combination (a member discount and a holiday sale?). With composition, one Checkout class plus small policy objects cover every case, and policies can even be combined by a policy that wraps two others.

This is also the idea behind dependency injection, which you'll meet in Spring (Advanced Java): a class receives the objects it depends on through its constructor instead of creating or inheriting them.

When inheritance is still right

Composition is the default, not a ban on extends. Inheritance fits when all of these hold:

  • There's a genuine, permanent is-a relationship, and a subclass object can be used anywhere the parent is expected without surprises (the Liskov substitution principle in SOLID).
  • The parent class is designed and documented for extension, like an abstract class with a template method, or a class from your own code base that you control.
  • You want the subclass to expose the whole parent API.

A quick test: if you'd describe the relationship with "has", "uses" or "is made of", use composition. If "is a kind of" is true in every situation, inheritance is an option. A Stack is not a kind of Vector (you shouldn't be able to insert in the middle of a stack), which is why the JDK's java.util.Stack extends Vector is considered a design mistake (Legacy Collections).

Common mistakes

  • Leaking internal parts. A getter that returns the internal List lets callers modify the whole's state. Return a copy or an unmodifiable view.
  • Storing what you're given without copying, when you meant composition rather than aggregation.
  • Inheriting just to reuse code. Extending ArrayList to get a Playlist exposes remove(int), clear() and more to every caller. Hold a list instead.
  • Forgetting null checks on injected parts. Objects.requireNonNull(policy) in the constructor fails fast with a clear message (The Object Class).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A University creates its Department objects in its constructor, keeps them private, and they're never shared. What relationship is that?

    The whole creates and exclusively owns its parts, which live and die with it. That's composition.
  2. 2. A Playlist stores references to Song objects that also appear in other playlists and in the library. What relationship is that?

    The songs exist independently and are shared among several wholes, so the playlist aggregates them.
  3. 3. In the TrackedSet extends HashSet example, why did addAll of 3 elements count 6 additions?

    The superclass implementation calls add() internally, and dynamic dispatch sends those calls to the subclass's add(), which counts again. This is the fragile base class problem.
  4. 4. Which is an advantage of delegating to an interface-typed field over subclassing?

    Because the field's type is an interface, any implementation (including a lambda) can be plugged in, even after the object is created.

Summary

  • Has-a relationships are expressed with fields that refer to other objects.
  • Association: one object uses another. Aggregation: a whole holds parts that exist independently and may be shared. Composition: a whole owns its parts, which live and die with it.
  • For composition, create or copy parts inside the whole, keep them private and don't return internal references.
  • Inheritance couples a subclass to its parent's implementation; overriding methods the parent calls internally can cause bugs like double counting.
  • Favor composition over inheritance: wrap an object and delegate to it to get encapsulation, flexibility and a smaller API.
  • Holding an interface-typed field (strategy, dependency injection) lets you change behavior without subclasses. Use inheritance for true, substitutable is-a relationships with classes designed for extension.

Next: Records, Java's compact syntax for immutable data classes, which make great parts for composition.