AlgoMaster Logo

Aggregation

Ashish

Ashish Pratap Singh

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.

1. What is Aggregation?

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.

Key Characteristics of Aggregation:

  • The whole and the part are logically connected.
  • The part can exist independently of the whole.
  • The whole does not own the part.
  • The part can be shared among multiple wholes.
  • Both the whole and the part can be created and destroyed independently.

If a class contains other classes for logical grouping only without lifecycle ownership, it is an aggregation.

2. Code Example

Let’s model the above example in code:

Usage:

  • Department groups Professor objects.
  • The professors are not created inside the Department class.
  • They can exist before, and survive after, the department’s existence.

If you delete the csDept object, the professors still exist in memory and could be reassigned to another department. That’s aggregation in action.

3. UML Representation

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.

4. When to Use Aggregation in OOP

Use aggregation when:

  • The part can exist independently of the whole.
  • The whole groups or organizes the parts logically.
  • The part might be shared across multiple wholes.
  • There is no ownership or lifecycle dependency.