Composition and Aggregation in OOP
What Are They?
Both composition and aggregation describe “has-a” relationships between classes, but they differ in dependency strength:
- Aggregation:
- A weaker relationship.
- The contained object (part) can exist independently of the container (whole).
- Composition:
- A stronger relationship.
- The contained object cannot exist without the container.
- Aggregation: A Library has Books – books can exist outside the library.
- Composition: A House has Rooms – if the house is destroyed, the rooms no longer exist.
Key Differences
| Aspect | Aggregation | Composition |
|---|---|---|
| Dependency | Parts are independent | Parts are dependent |
| Lifetime | Whole and part can have different lifetimes | Whole and part share the same lifetime |
| Example | Library–Book, Team–Player | Car–Engine, House–Room |
| UML representation | Hollow diamond ◇ | Filled diamond ◆ |
Why They Are Important
- Design Flexibility: Lets programmers model real-world relationships accurately.
- Code Reusability: Aggregation allows parts (e.g., books) to be reused in multiple wholes (e.g., different libraries).
- Encapsulation of Complexity: Composition hides the details of internal objects from the outside
Java (aggregation):
class Book {
String title;
}
class Library {
List<Book> books; // aggregation: books can exist without library
}Python (composition):
class Engine:
def start(self):
print("Engine starts")
class Car:
def __init__(self):
self.engine = Engine() # composition: engine tied to car
def start(self):
self.engine.start()- Use real-world analogies (Car–Engine vs Library–Book).
- Mention lifetime dependency (key difference).
- Draw UML diagrams if asked (Unified Modeling Language)
- Confusing aggregation with association (general “uses-a” is even weaker).
- Forgetting that composition implies ownership → destroying the whole destroys the parts.
- Thinking aggregation means “just a collection”: it specifically means independent existence.