
A
B
"Can you explain the difference between an interface and an abstract class, including when you would choose one over the other?"
An interface primarily defines a contract: what operations a type must support. An abstract class can also define a contract, but it is usually used when multiple subclasses should share common state or behavior.
from abc import ABC, abstractmethod
class Renderable(ABC):
@abstractmethod
def render(self):
pass
Interfaces traditionally focus on method signatures, while abstract classes can include partial implementations and reusable helper methods. This makes abstract classes useful when several subclasses would otherwise duplicate logic.
from abc import ABC, abstractmethod
class Shape(ABC):
def describe(self):
return 'shape'
@abstractmethod
def area(self):
pass
Abstract classes commonly hold instance variables and define constructors to initialize shared state. Interfaces generally do not own object state in the same way; they describe capabilities rather than shared object internals.
class Animal(ABC):
def __init__(self, name):
self.name = name
Interfaces are often preferred when unrelated classes need to expose the same behavior, because a class can usually implement multiple interfaces. Abstract classes are better when the relationship is truly an 'is-a' hierarchy with shared base logic.
class FileLogger(LoggerInterface, FlushableInterface):
pass
The exact distinction depends on the language. For example, Java and Kotlin have explicit interfaces and abstract classes, while Python uses abstract base classes and duck typing, so the conceptual difference matters more than the syntax.