Junior — Middle
Can you give an example of using an aggregation method in object-oriented programming?
sobes.tech AI
Answer from AI
Aggregation in object-oriented programming is a 'part-whole' relationship where an object of one class contains a reference to an object of another class, but the objects can exist independently.
Example in Python:
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self, engine):
self.engine = engine # Aggregation: the car contains an engine
def start(self):
self.engine.start()
print("Car is moving")
engine = Engine()
car = Car(engine)
car.start()
Here, Car aggregates an Engine object. The Engine can exist independently of the Car. If the Car object is destroyed, the Engine can continue to exist.