AlgoViz

Interface vs abstract class

medium 45 min

An interface says what something can do and leaves the how to others.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:42

Interface vs abstract class

1:03Reel

Theory

Read or listen first. About 3 min.

What it is

An interface is a named promise: a list of operations and what they mean. A class that implements it takes on the promise. The interface holds no data of the object, has no constructor, and says nothing about how the work is done. It describes what something can do.

An abstract class is a class that is not finished. It may hold fields, run a constructor, have private helpers and complete methods, and it may leave abstract methods as holes that a subclass must fill. Nobody can create an object of it directly. It describes what something is.

Both stop you from creating an incomplete thing, and both let one variable hold many classes. The difference is what comes along: a promise alone, or a promise with state and code.

Why it exists

Callers should depend on as little as possible. A method that takes a Flyable accepts a plane, a drone and the fake in a test. A method that takes a Vehicle accepts only things with that parent.

Implementers should not write the same code five times. If every vehicle has a name, a speed and the same way to start, one base class can hold that once and check it once.

In Java, C# and TypeScript a class has one parent class and any number of interfaces. The parent is a scarce resource. Spend it on real shared state, and use interfaces for everything else.

A short history

  1. 1996

    JDK 1.0 is released on 23 January with both tools in the language: classes may be abstract, a class extends one class and implements any number of interfaces.

  2. 2007

    PEP 3119 proposes abstract base classes for Python (created 18 April). They arrive with Python 2.6 on 1 October 2008 and with Python 3.0.

  3. 2014

    Java 8 (18 March) adds default methods, so that an interface of a library can grow without breaking code written for older versions.

  4. 2017

    Java 9 follows JEP 213 and allows private methods in interfaces, so that default methods can share a helper. In the same year PEP 544 proposes Python protocols: a class fits by its shape, without naming the protocol. They arrive in Python 3.8.

Words to know

Interface
A named set of operations without the state of an object.
Abstract class
A class that cannot be created directly, with any mix of finished and missing methods.
Abstract method
A method with a signature and no body. The first concrete subclass must supply it.
Concrete class
A class with no holes left. Objects can be created.
Default method
A method with a body inside an interface. It can only use the other operations.
Marker interface
An interface without methods that only labels a class, such as Serializable.
Skeletal class
An abstract class that implements most of an interface on top of a few primitives, such as AbstractList.
Nominal typing
A class fits because it says so: implements Flyable.
Structural typing
A class fits because it has the methods: TypeScript, Go, Python protocols.
ABC
Abstract base class, Python's tool for both ideas.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Ask what callers need. A promise: that is the interface

Understand it

Start here

The lantern parade

A town holds a parade at night. The workshop gives out bare wagons that the teams must finish. The light group takes anybody who glows. These are two different kinds of rule, and the whole topic is inside them.

Wagons and badges
your top here

Wagon: what it is, with parts included, one only. Badge: what it can do, no parts, as many as fit.

Apart first

The interface on its own

Take three capabilities. Drivable means drive and brake. Flyable means take_off, fly and land. Swimmable means sail and anchor. None of them says what the thing is made of. The only thing a caller learns is which calls are safe.

Python
from abc import ABC, abstractmethodclass Glows(ABC):    @abstractmethod    def light(self) -> int:        """Brightness from 1 to 10. Never 0."""class Bicycle(Glows):    def __init__(self, dynamo_speed): self.dynamo_speed = dynamo_speed    def light(self): return min(10, max(1, self.dynamo_speed // 2))class Lantern(Glows):    def light(self): return 4def light_group(members: list[Glows]) -> int:    return sum(m.light() for m in members)print(light_group([Bicycle(12), Lantern()]))   # 10class Drum(Glows):    passtry:    Drum()except TypeError as error:    print("refused:", error)
Two classes with nothing in common except one promise. The function knows the promise and no class.
Edit and run it in your browser

Python refuses Drum() when it is created. Java, C# and TypeScript refuse the class when it is compiled. Both are better than an error in the middle of the parade.

Apart first

The abstract class on its own

A vehicle has a name and a top speed. Every vehicle starts and stops in the same way. Only one thing is unknown: which kind it is. So the base class keeps the data, checks it, offers the finished methods, and leaves kind open.

Python
from abc import ABC, abstractmethodclass Vehicle(ABC):    def __init__(self, name, max_speed):        if max_speed <= 0:            raise ValueError("max_speed must be positive")        self.name, self.max_speed = name, max_speed    def start(self):                      # finished: everybody gets it        return f"{self.name} starts"    def label(self):                      # finished, but asks the hole        return f"{self.name} ({self.kind()}, {self.max_speed} km/h)"    @abstractmethod    def kind(self): ...                   # the holeclass Car(Vehicle):    def kind(self): return "land"print(Car("Dot", 200).label(), "|", Car("Dot", 200).start())try:    Car("Dot", -5)except ValueError as error:    print("refused:", error)
The constructor runs for every subclass. A negative speed is refused in one place.
Edit and run it in your browser

Look at label. The base class calls a method that does not exist yet. This is the start of the Template method pattern.

The bad shape: one parent that can do everything

Vehicle# name: String+ start()+ drive()+ fly()+ sail()

1/3One parent

All abilities are in the base class, because some vehicle needs each of them.

extends (is a)

The sign of it: methods that only throw. Abilities were mixed up with identity.

The good shape: one base, separate promises

«abstract»Vehicle# name: String# maxSpeed: int+ start()+ label()# kind()*

1/4What it is

The base holds state and code. The star marks the hole.

extends (is a)implements

Solid line with a triangle: extends. Dashed line with a triangle: implements.

Side by side

Eight questions, two answers

Java, unless another language is named

QuestionInterfaceAbstract class
PurposeCan-do: a capability, a contractIs-a: a base type, a half built object
MethodsAbstract, plus default, static (Java 8) and private (Java 9)Abstract and finished, in any mix
FieldsOnly constants: public static finalAny, also per object
How manyMany: implements A, B, COne: extends Base
ConstructorNoneYes. It runs when a subclass object is made
AccessMembers are public, except private helperspublic, protected, package or private
Shared codeOnly through default methods, without stateYes, with state
CouplingLooser: a promiseTighter: a child knows the parent's insides
The two rows that decide most real cases are fields and how many.

The same idea in other languages

LanguageInterfaceAbstract classSeveral parents with state?
PythonABC with only abstract methods, or typing.ProtocolABC with state and codeYes
TypeScriptinterface, fits by shape, gone at run timeabstract class, exists at run timeNo
C++Class with only pure virtual functions and a virtual destructorClass with at least one pure virtual functionYes
C#interface, with default members since C# 8abstract classNo
Gointerface, fits by its methods, nothing is declaredNone. Embed a structNo classes
Python and C++ allow several parents with state. What that costs is told in Multiple inheritance and The diamond problem.

At run time

Two ways to hold the same object

One SeaPlane can be held as a Vehicle, as a Flyable or as a Swimmable. The object does not change. The view changes: each type shows only the calls it promises.

The same object through two types

The garage cannot call fly, and the air show cannot call start. Each knows just enough.

Choose

Which one do I need?

A decision in four questions

Signs

  • Interface: unrelated classes

    A bicycle and a lantern both glow. They share no parent.

  • Interface: several at once

    One class needs two or more abilities.

  • Interface: an edge of the system

    Databases, mail, clocks. You want to swap the real one for a fake.

  • Abstract class: shared state

    Every child needs the same fields, checked in one constructor.

  • Abstract class: fixed order of steps

    The order stays, a step changes. A final method calls the holes.

  • Abstract class: it will grow

    You add finished methods later, and children in the same code base get them.

You need payments by card and by voucher. Both log, both retry. What do you write?

BreaksAn abstract class with everything
How
BasePayment with card number, voucher code, logging, retry and pay().
Limit
Voucher objects carry a card number. Every caller and every test drags the base along.
Choose when
Never.
WorksAn interface only
How
PaymentMethod.pay(cents), two classes.
Limit
Logging and retry are written twice and drift apart.
Choose when
As long as nothing is shared.
StrongInterface, and the shared work around it
How
PaymentMethod for callers. Retry and logging in a Decorator, or in a small abstract class if they need protected steps.
Limit
One more class to find.
Choose when
Two implementers share the same steps.

Both together

A promise, a skeleton, a class

The Java collections show the pair. List is what callers hold. AbstractList is a skeletal implementation that needs only get and size for a read only list. ArrayList extends the skeleton and also names the interface.

Who uses which part

The last box is why the interface must exist: someone whose parent is already taken can still be a List.

Use an interface when

  • You describe an ability or a contract
  • A class needs more than one of them
  • Unrelated classes share behaviour by name
  • You publish an API for strangers
  • You want loose coupling and easy fakes

An abstract class is better when

  • Children share state and code
  • A constructor must check something
  • Some steps need protected access
  • The classes are closely related
  • The base will grow with finished methods

Summary

The whole topic in one minute.

Interface: a promise, can-do, as many as you like, no state. Abstract class: a half built object, is-a, one parent in most languages, with state, constructor and code.

Start with the interface that the caller needs. Add an abstract class when two or more implementers really share state or a fixed sequence of steps. Keep the interface as the type of variables and parameters.

Adding a method to an interface breaks every implementer unless it has a default body. Adding a finished method to an abstract class usually does not. Plan for that before you publish either.

  • Interface: can-do, a promise, many. Abstract class: is-a, a half built object, one.
  • State, constructor and protected steps need a class.
  • Callers hold the interface. Implementers may start from the abstract class.
  • A new abstract method in an interface breaks every implementer. A default body does not.
  • If a child throws because it cannot do it, an ability was mixed up with identity.
  • One implementation and no boundary: a plain class is fine.

Sources