Sobes.tech
Middle

When should you use an abstract class and when an interface?

sobes.tech AI

Answer from AI

Abstract class:

  • When a common implementation of behavior is needed for subclasses, but flexibility in overriding some methods is required.
  • When classes have common fields of state (instance variables) that should be inherited.
  • When it is possible to define "kinship" between classes (the "is-a" relationship).
  • When a default implementation for most methods should be provided, requiring subclasses to implement only specific methods.

Interface:

  • When it is necessary to define a behavior contract that unrelated classes can implement.
  • When a class should have multiple types (multiple inheritance of type).
  • When flexibility and the ability to add new behavior without changing existing classes are important (through implementing a new interface).
  • When a strict separation between behavior definition and its implementation is required.
  • When it is necessary to model the "can be" relationship, "has-a" (although composition is often preferable for "has-a").

Example:

An abstract class Animal can have common fields age, name, and an implemented method eat(), but an abstract method makeSound(), which should be implemented by subclasses Dog and Cat.

The interface Flyable can be implemented by classes Bird and Airplane, which are otherwise unrelated and do not inherit from a common ancestor, but both can "fly".