Junior — Middle
Can you give an example of composition usage in object-oriented programming?
sobes.tech AI
Answer from AI
Composition in object-oriented programming is when one object contains another object as part of its structure, and the lifecycle of the nested object depends on the external one.
Example in Python:
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine() # Composition: the car contains an engine
def start(self):
self.engine.start()
print("Car is moving")
car = Car()
car.start()
Here, the Car object contains an Engine object. If the Car object is destroyed, the Engine also ceases to exist, which is the essence of composition.