Junior — Middle
Why is it preferable to use composition instead of inheritance when designing systems?
sobes.tech AI
Answer from AI
Composition is preferred over inheritance because it provides greater flexibility and loose coupling of components. In composition, an object contains other objects and delegates tasks to them instead of inheriting behavior and data from a base class.
Advantages of composition:
- Flexibility: you can dynamically change the components of an object at runtime.
- Avoidance of inheritance issues: there is no rigid hierarchy, which reduces the risk of errors related to multiple inheritance or changing the behavior of a base class.
- Code reuse: components can be used in different classes without duplication.
Example of composition in Python:
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
self.engine.start()
print("Car is moving")
engine = Engine()
car = Car(engine)
car.start()
Here, Car uses Engine through composition, not inheritance. This simplifies maintenance and code extension.