OOP of Object-Oriented Design (Study Notes)
Composition is a design principle where one class contains objects of other classes to reuse functionality instead of inheriting it.
Feature | Inheritance | Composition |
---|---|---|
Goal | Reuse behavior via “is-a” relationship | Reuse behavior via “has-a” relationship |
Coupling | Tight coupling | Loose coupling |
Flexibility | Less flexible to change | More flexible and modular |
Code Reuse | Inherits all parent behavior | Reuses specific behavior only when needed |
Use When | Natural hierarchy exists | You want to compose behavior dynamically |
Downsides | Fragile base class problem, tight coupling | May involve more boilerplate |
You want to combine behaviors flexibly.
You’re designing for loose coupling and testability.
You want to avoid unintended inheritance side effects.