Aggregation in Object-Oriented Programming (OOP) represents a "has-a" relationship between two classes, signifying that one class contains an instance of another class, but where the contained class can exist independently.
Understanding Aggregation
Aggregation is a form of association in OOP, specifically indicating a whole-part relationship. However, unlike composition (another type of association), aggregation implies that the part can exist independently of the whole. In other words, the "whole" class doesn't own the "part" class, and the "part" can be associated with other "whole" classes.
Key Characteristics
- "Has-a" Relationship: Expresses that one class has an instance of another class.
- Independent Existence: The contained object (the "part") can exist even if the container object (the "whole") is destroyed. This is the most important distinction from composition.
- Weak Relationship: The relationship between the two classes is relatively weak, meaning changes in one class are less likely to directly impact the other.
Example
Consider the relationship between a Department
and Professor
. A Department
has Professors
. However, if the Department
is closed, the Professors
still exist; they can be associated with other departments or institutions. This illustrates aggregation.
Code Example (Java)
class Professor {
String name;
public Professor(String name) {
this.name = name;
}
}
class Department {
String name;
Professor professor; // Aggregation: Department "has a" Professor
public Department(String name, Professor professor) {
this.name = name;
this.professor = professor;
}
}
public class Main {
public static void main(String[] args) {
Professor prof1 = new Professor("Dr. Smith");
Department dept1 = new Department("Computer Science", prof1);
// Even if 'dept1' is no longer needed, 'prof1' still exists.
dept1 = null;
System.out.println(prof1.name); // Output: Dr. Smith
}
}
In this example, the Department
class aggregates the Professor
class. Notice that prof1
continues to exist even after dept1
is set to null.
Aggregation vs. Composition
Feature | Aggregation | Composition |
---|---|---|
Relationship | "Has-a" | "Part-of" |
Ownership | No ownership; independent existence | Strong ownership; dependent existence |
Dependency | Weak; changes in one less likely to affect the other | Strong; changes in one significantly affect the other |
Lifecycle | Independent lifecycles | Dependent lifecycles |
When to Use Aggregation
Use aggregation when:
- You want to model a "has-a" relationship.
- The contained object should be able to exist independently.
- The lifecycle of the contained object is not tightly coupled to the lifecycle of the container object.
Aggregation provides a flexible way to model relationships between classes in OOP, allowing for reuse and maintainability.