Aggregation and Composition OOP
Aggregation and Composition OOP
OOP
Understanding Object Relationships
Overview
• Aggregation and Composition are ways to
model relationships between objects in OOP.
They help represent real-world scenarios
where objects are related to each other.
Aggregation
• Definition: A weak 'has-a' relationship where objects can exist independently.
• Code Example:
• class Department:
• def __init__(self, name):
• self.name = name
• class University:
• def __init__(self, name):
• self.departments = []
• self.name = name
• def add_department(self, department):
• self.departments.append(department)
Composition
• Definition: A strong 'has-a' relationship where objects cannot exist independently.
• Code Example:
• class Room:
• def __init__(self, name):
• self.name = name
• class House:
• def __init__(self, name):
• self.name = name
• self.rooms = [Room('Living Room'), Room('Bedroom'), Room('Kitchen')]
Key Differences
• Aggregation vs Composition:
• - Aggregation: Weak relationship, objects can
exist independently.
• - Composition: Strong relationship, objects cannot
exist independently.
• Real-World Examples:
• - Aggregation: University and Departments.
• - Composition: House and Rooms.
Conclusion
• Aggregation and Composition are essential
concepts in OOP to represent relationships.