Association, Aggregation & Composition
TL;DR
These terms describe relationships between objects (HAS-A relationships), ordered by strictness:
- Association: The broadest relationship. Two objects know about each other but have independent lifecycles (e.g.,
TeacherandStudent). - Aggregation: A “weak” HAS-A relationship. The child can exist independently of the parent (e.g.,
DepartmentandProfessor). - Composition: A “strong” HAS-A relationship. The child cannot exist without the parent (e.g.,
HouseandRoom).
Concept
Association (Uses-A)
Any relationship where two distinct classes are linked. It can be one-to-one, one-to-many, etc. There is no strict ownership.
Aggregation (Has-A, Weak Ownership)
A specialized form of Association. The parent object holds a reference to a child object. If the parent object is destroyed, the child object still survives and can be attached to another parent.
Composition (Has-A, Strong Ownership)
A strict form of Aggregation. The parent entirely owns the child. The child lifecycle is bound to the parent. If the parent dies, the child is destroyed too.
Examples
// --- 1. AGGREGATION (Weak) ---
class Professor {}
class Department {
List<Professor> professors;
// Professors are passed in. If Department is deleted,
// the Professors still exist in memory!
public void setProfessors(List<Professor> professors) {
this.professors = professors;
}
}
// --- 2. COMPOSITION (Strong) ---
class Room {}
class House {
private final Room kitchen;
public House() {
// The House creates the Room.
// If the House is garbage collected, the kitchen is destroyed too.
this.kitchen = new Room();
}
}
Interview Questions
Q: How does Java enforce Composition vs Aggregation?
A: Java does not have dedicated keywords for these concepts. They are architectural design patterns.
- Aggregation is usually implemented by passing the child object into the parent via a constructor or setter (Dependency Injection).
- Composition is usually implemented by having the parent instantiate the child object directly within its own constructor.
Q: Give a real-world software example of Composition.
A: A File and its FileDescriptor. If the File object is closed and destroyed, the FileDescriptor is inherently destroyed and useless. Another example is a GUI Window and a Button inside it. If the window is destroyed, the button goes with it.