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.
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 existsKey code pattern: the part is created outside and passed in to the whole.
Reading the Department example
- The
Teacherobjectt1is created before the department exists, outside the Department class. addTeacher(t1)stores a reference to the teacher in the department's list. No new teacher is created.- When
dis set tonull, the Department object can be garbage-collected. Butt1still refers to the teacher, so the teacher stays alive, andt1.getName()still prints "Ms. Perera".
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:
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 departmentsThis is impossible in composition, where each part belongs to exactly one whole.
How to recognise aggregation
- The sentence "X has Ys" is true (a Team has Players), and
- a Y still makes sense without the X (a player can leave the team and join another), and
- the Ys are usually created somewhere else and then added to the whole.
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.