Association, Aggregation and Composition

Naveen AnamaneniUpdated · 5 min read

A patient visits a doctor; neither belongs to the other. A cricket team has players, who can move to another team. A house owns its rooms; demolish the house and the rooms are gone too. These are three different strengths of relationship, and object-oriented design gives each a name: association, aggregation and composition. Interviewers love asking for the difference.

Three Strengths of Relationship

Uses, has, owns
AssociationAggregationComposition
Meaning"uses" or "works with""has", loosely"owns", strongly
ExamplePatient and DoctorTeam and PlayerHouse and Room
Can the part exist alone?Both are independentYesNo
Who creates the part?Someone elseUsually someone elseThe whole
LifetimeIndependentIndependentTied to the whole
UML symbolPlain lineHollow diamond ◇Filled diamond ◆

In Code

Relations.java▶ Try it
public class Relations {
    static class Doctor {
        String name;
        Doctor(String name) { this.name = name; }
        String treat(Patient p) { return name + " treats " + p.name; }
    }
 
    static class Patient {
        String name;
        Patient(String name) { this.name = name; }
    }
 
    static class House {
        private final Room[] rooms;
 
        House(String... roomNames) {
            rooms = new Room[roomNames.length];
            for (int i = 0; i < roomNames.length; i++) {
                rooms[i] = new Room(roomNames[i]);
            }
        }
 
        int roomCount() { return rooms.length; }
 
        private static class Room {
            final String name;
            Room(String name) { this.name = name; }
        }
    }
 
    public static void main(String[] args) {
        Doctor doctor = new Doctor("Dr. Advitha");
        Patient patient = new Patient("Navika");
        System.out.println(doctor.treat(patient));
 
        House home = new House("Hall", "Kitchen", "Bedroom");
        System.out.println("Rooms: " + home.roomCount());
    }
}
Output
Dr. Advitha treats Navika
Rooms: 3

How it works

  1. Association: Doctor.treat(Patient p) uses a patient for one job. The doctor doesn't keep or own the patient; both exist independently.
  2. Composition: House creates its own Room objects inside its constructor (line 19), keeps them private, and never hands them out. Nobody else refers to them, so when the house becomes garbage, so do the rooms. Room is even a private nested class, so only House can create one.
  3. Aggregation is the department-and-employees example from the previous lesson: parts created elsewhere and passed in.

Try it yourself: add a method void addRoom(String name) to House. Should it create the Room itself, or accept a Room from outside? Why?

How to Tell Them Apart in Java

Java has no special keyword for any of the three. The difference is in who creates the part and who else can reach it:

AskCompositionAggregation
Is the part created inside the whole?YesUsually no; it's passed in
Can outside code get a reference to the part?No (or only a copy)Yes
Can the part be shared by several wholes?NoYes

Common Mistakes

Calling every field "composition". If the part is passed in and shared, it's aggregation.

Leaking composed parts. A getter that returns the internal rooms array turns composition into accidental sharing; return a copy.

Using inheritance for any of these. All three are has-a or uses-a relationships, never is-a.

Interview Corner

What is the difference between association, aggregation and composition?

Association is any relationship where objects use or know each other, with independent lifetimes, such as a doctor and a patient. Aggregation is a has-a association where the part can exist without the whole and can be shared, such as a team and its players. Composition is a strong has-a where the whole creates and owns the part, and the part's lifetime is tied to the whole, such as a house and its rooms.

Practice

  1. Easy: Classify each: Car and Engine; Library and Member; Order and OrderLine; Student and Course.
  2. Harder: Model Order (composition with OrderLines it creates) and Customer (aggregation, passed in). Print an order's total.

Quick check: Association, aggregation, composition

4 questions
1Which relationship ties the part's lifetime to the whole?
2A team has players who can join other teams. That's:
3A doctor treats a patient during an appointment. That's:
4Which UML symbol marks composition?

Key Takeaways

Was this tutorial helpful?

Lesson 118 of 482