Junior — Middle
What is the difference between using composition and aggregation in class and object design?
sobes.tech AI
Answer from AI
Composition and aggregation are two types of relationships between objects in object-oriented design.
-
Composition is a "part-whole" relationship where the part cannot exist without the whole. If the whole object is destroyed, its parts are also destroyed. Example: class
Carand classEngine. The engine exists only inside the car. -
Aggregation is a weaker relationship where the part can exist independently of the whole. For example, class
Classand classStudent. A student can exist without being associated with a specific class.
Example in Python:
class Engine:
pass
class Car:
def __init__(self):
self.engine = Engine() # composition
class Student:
pass
class SchoolClass:
def __init__(self, students):
self.students = students # aggregation
s1 = Student()
s2 = Student()
class1 = SchoolClass([s1, s2])
Here, Engine is created inside Car and does not exist separately, whereas Student is created independently and passed into SchoolClass.