Unit 4 · Association, Aggregation and Composition

4.2Aggregation

Aggregation is an association with a whole and its parts: one object collects or groups others. The parts, however, have a life of their own.

Aggregation is a special, weaker form of "has-a": a whole contains parts, but the parts can exist independently of the whole. It is called a "has-a, but not owned" relationship.

Examples: a Department has Teachers (the teachers still exist if the department closes); a Team has Players; a Library has Books.

Java
class Department {
    private String name;
    private java.util.List<Teacher> teachers = new java.util.ArrayList<>();

    Department(String name) { this.name = name; }

    void addTeacher(Teacher t) { teachers.add(t); }   // teacher created OUTSIDE

    void showStaff() {
        for (Teacher t : teachers) System.out.println(t.getName());
    }
}

Teacher t1 = new Teacher("Ms. Perera");     // exists independently
Department d = new Department("Computing");
d.addTeacher(t1);
d = null;                                    // department gone
System.out.println(t1.getName());            // teacher still exists

Key code pattern: the part is created outside and passed in to the whole.

DepartmentTeacher10..*hasparts are passed in and can outlive the whole
Aggregation (hollow diamond at the whole): the Teacher is created outside and survives if the Department is removed

Reading the Department example

The department has teachers, but it does not own them.

Sharing parts

Because parts are created outside, the same part can belong to more than one whole at once:

Java
Teacher t2 = new Teacher("Mr. Silva");
Department computing = new Department("Computing");
Department maths = new Department("Mathematics");
computing.addTeacher(t2);
maths.addTeacher(t2);          // the same teacher works in both departments

This is impossible in composition, where each part belongs to exactly one whole.

How to recognise aggregation

In UML, aggregation is drawn as a line with a hollow diamond at the whole (Department) end.

Some textbooks treat aggregation as just a kind of association, and some modelling tools rarely use it. What matters in your designs is the question it asks: if the whole is removed, should the parts survive? For aggregation the answer is yes.

Remember

  • Aggregation is a has-a relationship in which the parts can exist without the whole.
  • The parts are created outside and passed in; they can be shared.
  • UML: a hollow diamond at the whole.