Aggregation
About
Aggregation is an object-oriented design principle where one object contains another object in a weakly coupled manner. It represents a "has-a" relationship, but unlike composition, the contained object can exist independently of the containing object.
Key Idea: An object (container) holds references to other objects, but those objects can exist independently.
Aggregation is not considered as one of the four fundamental OOP principles (Encapsulation, Abstraction, Inheritance, and Polymorphism). However, it is an important design concept within OOP.
Composition = Strong Ownership Aggregation = Weak Ownership
Types of Aggregation
1. Simple Aggregation (Loose Coupling)
Contained objects can exist independently.
Objects are referenced via pointers.
Represented by an empty diamond in UML.
Example: A Team
has Players
, but players exist without the team.
2. Shared Aggregation (Shared Ownership)
A single object belongs to multiple containers.
If one container is deleted, the object still exists.
Example: A
Book
is in multipleLibraries
.
Example: A Library
contains Books
, but books exist in multiple libraries.
Aggregation vs. Composition vs. Inheritance
Comparison
Feature
Aggregation
Composition
Inheritance
Relationship
"Has-a" (University has Students)
"Has-a" (Car has an Engine)
"Is-a" (Car is a Vehicle)
Coupling
Loose
Strong
Tight
Lifespan Dependency
Independent (Student exists without University)
Dependent (Engine dies with Car)
Dependent
Code Reusability
High
Moderate
Limited
Encapsulation
Strong
Strong
Weaker
Flexibility
More Flexible
Less Flexible
Fixed
Example
A Team
has Players
but they exist independently.
A Car
has an Engine
, which doesn't make sense alone.
A Car
extends Vehicle
(fixed behavior).
Code Example
Bad Example (Using Inheritance Incorrectly)
Problem: A University
is not a Student
but contains students.
Good Example (Using Aggregation Correctly)
Correct Design: Students exist independently from the University
.
Last updated
Was this helpful?