In the last chapter, we explored Association, the fundamental "uses-a" relationship that connects independent objects, like a doctor and their patients. We learned that in an association, objects have their own lifecycles.
But what happens when the relationship is a bit tighter? What if one class represents a "whole" and another represents a "part" of that whole?
Think of a university department and its professors, a team and its players, or a playlist and its songs.
This is where Aggregation comes in. It’s a specialized, stronger form of association that models a "whole-part" relationship.
Aggregation represents a "has-a" relationship between two classes, where one class (the whole) groups or organizes other classes (the parts), but does not control their lifecycle.
If a class contains other classes for logical grouping only without lifecycle ownership, it is an aggregation.
Let’s consider a university context:
This relationship models Aggregation—the department and professors are linked, but their lifecycles are not tightly coupled.
Let’s model the above example in code:
Department
groups Professor
objects.Department
class.If you delete the csDept
object, the professors still exist in memory and could be reassigned to another department. That’s aggregation in action.
In UML class diagrams, aggregation is represented by a hollow diamond (◇) at the “whole” (container) side of the relationship.
This reads as: A Department has Professors, but it does not own them.
Use aggregation when: