Fundamentals · Medium · Free
What is inheritance? When is composition preferred over inheritance?
FresherFundamentalsOOP & Language Fundamentals
Inheritance vs composition
Inheritance (extends) reuses and specializes parent behavior. Composition builds behavior by delegating to contained objects—often safer when behavior combinations multiply.
- Use inheritance for true is-a relationships with stable hierarchy.
- Prefer has-a composition when you need mix-and-match features (favor composition over inheritance).
- Deep trees couple subclasses to parent changes—fragile base class problem.
java
class EmailSender { void send(String msg) { /* SMTP */ } }
class OrderService {
private final EmailSender mailer; // composition
OrderService(EmailSender m) { mailer = m; }
}Say you'd inject dependencies (composition) for testability with mocks.