Definition
Inheritance is an "is-a" relationship where a subclass extends a parent class and inherits its attributes and behaviors. Composition is a "has-a" relationship where an object contains instances of other classes to achieve functionality.
Core Problem They Solve
Both enable code reuse, but through different mechanisms. Inheritance promotes reuse through class hierarchies, while composition achieves reuse through object collaboration. The choice between them fundamentally impacts design flexibility, maintainability, and coupling.
Key Distinction
Inheritance (is-a): A Car is a Vehicle. The car inherits all vehicle properties and can override or extend them.
Composition (has-a): A Car has an Engine. The car contains an engine object and delegates engine-related operations to it.
Interview Tip: Always ask clarifying questions about the domain before choosing between inheritance and composition. If the relationship can be expressed as "is a type of," consider inheritance. If it is "is composed of parts," use composition.
When Each Applies
Use inheritance when there is a clear hierarchical relationship with shared behavior that follows the Liskov Substitution Principle (LSP). A SavingsAccount can substitute for Account anywhere in the system.
Use composition when you need flexibility to change behavior at runtime or when the relationship is about capability rather than identity. A PaymentProcessor has a PaymentGateway, and you can swap gateways without changing the processor's type.
✓Inheritance creates 'is-a' relationships through class hierarchies
✓Composition creates 'has-a' relationships through object containment
✓Inheritance enables polymorphism but creates tight coupling
✓Composition provides flexibility and loose coupling
✓The design principle 'favor composition over inheritance' guides modern OOP design
1Vehicle-Car-Truck inheritance hierarchy
2Car composed of Engine, Transmission, and Wheels
3Account-SavingsAccount-CheckingAccount hierarchy
4PaymentProcessor composed of PaymentGateway and TransactionValidator