0% found this document useful (0 votes)
3 views7 pages

Aggregation and Composition OOP

Uploaded by

airah Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Aggregation and Composition OOP

Uploaded by

airah Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Aggregation and Composition in

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.

• Example: A University 'has' multiple Departments.


• If the University is deleted, Departments can still exist.

• 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.

• Example: A House 'has' multiple Rooms.


• If the House is destroyed, the Rooms are also destroyed.

• 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.

• They help model real-world scenarios in


programming and are fundamental for
designing robust systems.
Comparison Table
Aspect Inheritance Aggregation Composition

Relationship "is-a" "has-a" (weak "has-a" (strong


ownership) ownership)
Coupling Tight Loose Strong

Lifecycle Child depends on Independent Dependent on


Dependency parent lifecycle parent
Reusability High Medium Medium

Flexibility Less flexible (fixed More flexible Less flexible


hierarchy)
Example SQLDatabase "is-a" DatabaseManager DatabaseServer
Database "has-a" Database "has-a"
ConnectionPool
Use Case Shared behavior, Loose relation, Strong ownership
tight relation collaboration and dependency

You might also like