Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 12

Association, aggregation, composition

Three strengths of HAS-A, told apart by lifetime and ownership

22m55 XP
→→→

What you'll be able to do

  • Distinguish association, aggregation and composition in real code
  • Read ownership from the constructor: created inside vs passed in
  • Store a collection of parts and iterate over them
  • Explain why the distinction matters for deletion and reuse
1

Association

Association: objects that simply know each other

The weakest link. Two objects are connected so they can collaborate, but neither owns the other and neither is a part of the other. - A Teacher teaches Students; both exist perfectly well on their own. - A Doctor treats Patients. - An Order references a Customer. It may be unidirectional (only one side holds the reference) or bidirectional (both do). Prefer unidirectional: two-way links must be kept in sync and are a classic source of bugs.

A one-way association
Main.java
1class Customer {
2 private String name;
3
4 Customer(String name) {
5 this.name = name;
6 }
7
8 String getName() {
9 return name;
10 }
11}
12
13class Order {
14 private Customer customer; // knows a customer, does not own one
15 private double total;
16
17 Order(Customer customer, double total) {
18 this.customer = customer;
19 this.total = total;
20 }
21}
Deleting the order must not delete the customer — that independence is what makes this an association rather than composition.
2

Aggregation

Aggregation vs composition: who owns the part?

A team is made of players, and a house is made of rooms. Delete the team and the players go home; delete the house and the rooms are gone forever.

Both are whole–part relationships. The difference is lifetime ownership, and in code you usually read it straight off the constructor: - Aggregation — the part is passed in from outside: Team(Player[] players). The part existed before the whole and survives it. Also called a *weak* HAS-A. - Composition — the whole creates the part: House() { this.rooms = new Room[...]; }. The part is born and dies with the whole. A *strong* HAS-A. The practical consequences show up when things are deleted or shared: an aggregated part may be shared between several wholes; a composed part must not be handed out at all.

Read the constructor

Aggregation (weak)

part passed in

Main.java
1class Team {
2 private Player[] players;
3
4 void add(Player player) { // comes from outside
5 ...
6 }
7}
  • Player exists before and after the Team
  • The same Player may join another Team
  • Deleting the Team deletes no players
  • UML: hollow diamond

Composition (strong)

part created inside

Main.java
1class House {
2 private Room[] rooms;
3
4 House(int count) {
5 rooms = new Room[count]; // born here
6 }
7}
  • Rooms have no life outside the House
  • They are never shared with another House
  • Deleting the House deletes the rooms
  • UML: filled diamond
Aggregation: the team does not own the players

Add the same Player to a second Team — legal, and a good demonstration of why this is aggregation rather than composition.

Output
Press Run to execute this example.

All four relationships at a glance

RelationshipJava shapeLifetimeExample
Inheritance (IS-A)class B extends Asame objectSavingsAccount / Account
Associationfield, no ownershipindependentOrder / Customer
Aggregationfield, part passed inpart survives the wholeTeam / Player
Compositionfield, part created insidepart dies with the wholeHouse / Room

In everyday conversation developers say 'composition' for all three HAS-A forms. Use the precise words when the lifetime actually matters — and in exams.

Composition leaks through getters

If House.getRooms() returns the internal array, callers can modify the rooms behind the house's back — encapsulation from Module 4 is broken. Return a copy, or expose only the operations you intend (house.addFurniture(...)).

Prove it — coding challenges

Common mistakes

WrongCalling every HAS-A relationship 'composition' in an exam answer.
WhyThe examiner is usually testing whether you can justify the lifetime difference.
FixSay which one and why: 'aggregation, because the players exist without the team'.
WrongCreating the part inside the constructor when callers must supply it.
WhyYou force one implementation and make testing hard — the class can no longer be given a fake collaborator.
FixAccept the collaborator as a constructor parameter (dependency injection) when it is shared or swappable.
WrongStoring parts in an array without tracking how many are used.
Why`players.length` is the capacity, not the count — you will print nulls.
FixKeep a `count` field and loop to `count` (or use `ArrayList`).

Lesson playground

Free practice

A playlist aggregates songs. Add a `remove` idea or a `total()` method — and note that the songs still exist if the playlist is thrown away.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

One player, two teams. What is printed?

Main.java
1class Player {
2 private String name;
3
4 Player(String name) {
5 this.name = name;
6 }
7
8 String getName() {
9 return name;
10 }
11}
12
13class Team {
14 private String teamName;
15 private Player captain;
16
17 Team(String teamName, Player captain) {
18 this.teamName = teamName;
19 this.captain = captain;
20 }
21
22 void show() {
23 System.out.println(teamName + " captain: " + captain.getName());
24 }
25}
26
27public class Main {
28 public static void main(String[] args) {
29 Player sara = new Player("Sara");
30
31 Team club = new Team("Falcons", sara);
32 Team national = new Team("Egypt", sara);
33
34 club.show();
35 national.show();
36 }
37}

Summary

  • Association: objects know each other, no ownership.
  • Aggregation: whole–part, part passed in and outlives the whole.
  • Composition: whole–part, part created inside and dies with the whole.
  • Read the constructor to tell them apart, and never leak an internal collection.