Skip to the page

OOP and SOLID · mid

Inheritance, composition and interfaces

Inheritance multiplies classes when behaviour varies in several ways. Composition holds the varying parts as objects and combines them at run time. Choose interface or abstract class by whether you share state and code.

The notes

What you must know

  • Channels times urgency times scheduling grows as a product of classes when each combination is a subclass, and each new dimension doubles the count.
  • Composition: a Notification holds a Channel (email, SMS, WhatsApp), a Priority and a DeliveryPolicy (now, scheduled, quiet hours). Each new option is one class and combinations are made at run time.
  • Inheritance fits a true, stable is-a with shared behaviour in a small fixed hierarchy, such as a template method in a framework base class.
  • The fragile base class problem: a change in the parent silently changes every child, because subclasses depend on parent internals.
  • Decorator is layered composition: wrapping a sender with retry or logging.
  • Interface: a contract or capability with no shared state; a class can implement many. Abstract class: shared state and code plus some abstract steps; single inheritance. Example template method: process() does validate, then abstract callGateway(), then record, then notify.
  • Java 8 default methods let you add to an interface without breaking implementers, but interfaces still cannot hold instance fields or constructors. Java 17 sealed types limit who may implement them. In TypeScript an interface exists only at compile time, an abstract class exists at run time.
  • Default choice: start with an interface, and add an abstract class only when real shared code appears.

The red pen

Common traps: mistake → fix

  • Mistake: Inheritance is always bad

    Fix: it is fine for a stable is-a with a small hierarchy.

  • Mistake: Abstract classes are faster than interfaces

    Fix: speed is not the reason to choose.

  • Mistake: Interfaces cannot have method bodies

    Fix: that is outdated since Java 8.

  • Mistake: Using composition but still switching on a type string inside

    Fix: the type switch is the problem, not the field.

Easy to hard

Questions interviewers ask, easy to hard

  1. Inheritance or composition for a notification system with channels, priorities and schedules?
  2. What is the fragile base class problem?
  3. Interface or abstract class: how do you choose?
  4. What does a sealed interface give you?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview