Composition vs Inheritance
Choosing the right approach
Interview Relevant: Design decisions
Composition vs Inheritance
Prefer composition (has-a) over inheritance (is-a) for flexibility.
Code Examples
python
1# Inheritance (Tight coupling)
2class Engine:
3 def start(self): pass
4
5class Car(Engine):
6 pass
7
8# Composition (Loose coupling)
9class Car:
10 def __init__(self):
11 self.engine = Engine()
12
13 def start(self):
14 self.engine.start()