03 / 13

Compare Abstract Classes and Interfaces. When would you choose one over the other?

Difficulty: 3/10

Abstract Class vs Interface

An abstract class is best when I have a strong base-type relationship and need to share state, constructors, invariants or implementation. An interface is better when I want to define a capability or contract that unrelated types can implement and I want low coupling. Modern Java and C# interfaces can also contain default implementations, so the distinction is no longer simply 'interface has no implementation'. The design decision should be based on ownership, substitutability, state and extension requirements rather than syntax alone.

javascript
  1. 1

    Abstract class: useful for shared state and implementation.

  2. 2

    Interface: useful for contracts and capabilities.

  3. 3

    A class can generally implement multiple interfaces.

  4. 4

    A class can extend only one class in Java/C#.

  5. 5

    Interfaces are usually preferable for dependency boundaries.

  6. 6

    Abstract classes are useful when lifecycle or invariant management belongs in the base class.

Follow-up Questions

  • Can interfaces contain state?
  • Can an abstract class implement multiple interfaces?
  • When is an interface a better dependency boundary?
  • Can an abstract class have static methods?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.