Inheritance vs Composition
When to use Composition?
- You want to combine behaviors flexibly.
- You’re designing for loose coupling and testability.
- You want to avoid unintended inheritance side effects.
Inheritance vs Composition Minimal example
Inheritance
Composition
Example: Car and Engine
Inheritance (bad design): Using inheritance wrongly can produce inflexible code. In this example, Car inherits from Engine – implying “Car is an Engine,” which is semantically incorrect. This violates design clarity (a subclass shouldn’t introduce impossible behavior) and tightly couples Car to Engine.car.start() prints: