Inheritance represents an IS-A relationship.
A child class inherits properties and methods from a parent class.
Example :
Python
class Engine: def start(self): print("Engine started") class Car(Engine): pass c = Car() c.start() #output Engine started What is Composition ?
Composition represents a HAS-A relationship.
One class contains an object of another class instead of inheriting from it.
Example :
Python
class Engine: def start(self): print("Engine started") class Car: def __init__(self): self.engine = Engine() def drive(self): self.engine.start() print("Car is driving") c = Car() c.drive() #output Engine started Car is driving | Feature | Inheritance | Composition |
|---|---|---|
| Relationship | IS-A | HAS-A |
| Coupling | Tight | Loose |
| Flexibility | Less | More |
| Reusability | Limited | High |
| Change impact | Affects child classes | Minimal |
| Preferred approach | Less | ✔ More (recommended) |