Inheritence vs Composition
- Head to Head comparision
| Topic | Inheritence | Composition |
| —— | ———- | ———- |
| Relationship | IS-A child is type of parent | HAS-A class owns component |
| Re-use Method | Automatic via class hierarchy | Explicit delegation to components|
| Coupling | Tight – child depends on | Loose – components are independent |
| Flexibility | Fixed – At class definition time | Swap components at run-time |
| Override | Override methods in child class | Pass a different object |
| Testing | Test child requires testing parent | Test each component in isolation |
| Best for | specialized types that share clear behavior | Pluggable feature, cross cutting concerns |
Lets take a simple composition
-
Lets take two classes
- BankAccount
- Card
-
Refer Here for notebook
