Object-oriented basics · Chapter 4

Interfaces and polymorphism

One call, many behaviours. How interfaces and dynamic dispatch replace type checks, overriding vs overloading, abstract classes vs interfaces, and duck typing in Python.

IntermediateInterview priority: High50 min
On this page
  1. The problem: asking every object what it is
  2. The idea: one promise, many answers
  3. How it works: static type, run-time type, dynamic dispatch
  4. Overriding vs overloading
  5. Abstract classes vs interfaces
  6. Program to an interface
  7. When not to use it
  8. In the interview
  9. Quiz

The problem: asking every object what it is

A drawing app stores circles and rectangles in one list. To total the area, the first version asks each object for its type:

double total = 0;
for (Object s : shapes) {
    if (s instanceof Circle c) {
        total += Math.PI * c.radius * c.radius;
    } else if (s instanceof Rect r) {
        total += r.width * r.height;
    }
}

The same chain appears in the renderer, the exporter and the hit-tester. When a Triangle arrives, someone has to find every chain and add a branch. Miss one and triangles are silently skipped: no error, just a wrong total.

The same instanceof chain, everywhere

  1. Without polymorphism you end up asking “what type are you?” everywhere. Every class that deals with shapes grows the same if/else chain of instanceof checks.

The idea: one promise, many answers

An interface is a promise: "anything that implements Shape has an area() method". It says what a class can do, not how. Code that only needs an area can then accept any Shape and call area() without knowing or caring which shape it got.

Polymorphism ("many forms") is what makes that call work: at run time, s.area() runs the version belonging to the object s actually refers to. A circle answers like a circle, a rectangle like a rectangle.

An interface, and the same call answered differently

  1. An interface is a promise. “Anything that implements Shape must have an area() method.” It says what a class can do, not how.
  2. Polymorphism means “many shapes”: the same call runs different code depending on the real object. The loop just says s.area(), and each object answers in its own way.

The type check has not disappeared; it has moved into the language. Instead of you writing if chains, the runtime picks the right method for you, every time, in every place.

How it works: static type, run-time type, dynamic dispatch

Every variable has two types worth knowing:

Static (declared) typeRun-time (actual) type
In Shape s = new Circle(2);ShapeCircle
DecidedWhen the code compilesWhen the object is created
ControlsWhich methods you are allowed to callWhich implementation actually runs

The compiler only lets you call s.area() because Shape declares it. When the line runs, the JVM looks at the object's real class and calls Circle.area(). This run-time choice is dynamic dispatch (also called late binding). The method in a subclass or implementing class that replaces the declared one is an override.

import java.util.List;

interface Shape {
    double area();
    default String describe() {                     // shared code is allowed in interfaces since Java 8
        return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
    }
}

record Circle(double radius) implements Shape {
    public double area() { return Math.PI * radius * radius; }
}

record Rect(double width, double height) implements Shape {
    public double area() { return width * height; }
}

record Triangle(double a, double b, double c) implements Shape {
    public Triangle {
        if (a + b <= c || a + c <= b || b + c <= a) throw new IllegalArgumentException("not a triangle");
    }
    public double area() {                          // Heron's formula
        double s = (a + b + c) / 2;
        return Math.sqrt(s * (s - a) * (s - b) * (s - c));
    }
}

public class Main {
    static double totalArea(List<? extends Shape> shapes) {
        double total = 0;
        for (Shape s : shapes) total += s.area();   // no instanceof: each object answers
        return total;
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3), new Triangle(3, 4, 5));
        for (Shape s : shapes) System.out.println(s.describe());
        System.out.printf("total %.2f%n", totalArea(shapes));   // total 15.14
    }
}

Adding a new shape means writing one class. totalArea, the renderer and everything else that works on Shape stay untouched: the open/closed principle in action.

A new shape is one new class; nothing else changes

  1. Now add a Triangle. With an interface, you write one new class that keeps the Shape promise. The loop, the renderer and everything else stay exactly as they are.
How dynamic dispatch is implemented

In the JVM (and C++), each class has a virtual method table (vtable): an array of pointers to its method implementations, with an overriding method stored in the same slot as the method it overrides. A virtual call loads the object's class pointer, indexes the table and jumps: a couple of memory reads, a few nanoseconds at most. Interface calls need a slightly slower lookup. In practice the JIT compiler watches each call site, and if it only ever sees one class (a monomorphic call site) it inlines the method, making the call free. Python looks methods up by name through the class's MRO on each call (with caching), which is why Python method calls cost tens of nanoseconds rather than one or two.

Overriding vs overloading

These sound alike and are decided at different times, which interviewers love to test.

OverridingOverloading
WhatSubclass replaces a method with the same signatureSame class has methods with the same name, different parameters
ChosenAt run time, by the object's actual classAt compile time, by the arguments' declared types
ExampleCircle.area() overrides Shape.area()print(int), print(String)
PythonYesNo: a second def with the same name replaces the first; use default arguments or functools.singledispatch

The trap, in Java:

static String greet(Object o) { return "object"; }
static String greet(String s) { return "string"; }

Object x = "hello";
greet(x);      // "object": overloads are picked by the declared type (Object), not the run-time type

Abstract classes vs interfaces

Both declare methods without implementing them, and both can be used as a type. They differ in what else they can hold.

InterfaceAbstract class
A class can haveMany (implements A, B, C)One (extends Base)
Instance fields (state)No (constants only)Yes
ConstructorsNoYes, to set up shared state
Method bodiesdefault and static (Java 8+), private (Java 9+)Any
Expresses"can do": a capability"is a kind of", with shared state and steps
Use whenUnrelated classes should be usable the same wayClosely related classes share fields and an algorithm skeleton

A common, strong combination: an interface as the public type, and an optional abstract base class that implements the boring parts. Java's own List (interface) and AbstractList (abstract base) work this way.

import java.util.ArrayList;
import java.util.List;

interface Refundable {                                   // a capability only some methods have
    void refund(long cents);
}

abstract class PaymentMethod {
    private final List<String> log = new ArrayList<>(); // shared state

    public final void pay(long cents) {                 // shared steps, not overridable
        if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
        charge(cents);                                  // dynamic dispatch to the subclass
        log.add(name() + " charged " + cents);
    }

    protected abstract void charge(long cents);         // the step that varies
    protected abstract String name();
    public List<String> log() { return List.copyOf(log); }
}

class Card extends PaymentMethod implements Refundable {
    protected void charge(long cents) { System.out.println("card network: " + cents); }
    protected String name() { return "card"; }
    public void refund(long cents) { System.out.println("card refund: " + cents); }
}

class GiftVoucher extends PaymentMethod {                // vouchers cannot be refunded
    private long remaining;
    GiftVoucher(long remaining) { this.remaining = remaining; }
    protected void charge(long cents) {
        if (cents > remaining) throw new IllegalStateException("voucher too small");
        remaining -= cents;
    }
    protected String name() { return "voucher"; }
}

public class Checkout {
    public static void main(String[] args) {
        List<PaymentMethod> methods = List.of(new Card(), new GiftVoucher(5_000));
        for (PaymentMethod m : methods) {
            m.pay(1_500);
            if (m instanceof Refundable r) r.refund(500);   // ask for the capability, not the class
            System.out.println(m.log());
        }
    }
}

pay() is a small Template Method: the abstract class fixes the steps and subclasses fill in charge. Refundable is an interface because refunds are a capability that cuts across the hierarchy. Checking for a capability interface is fine; checking for concrete classes (instanceof Card) is the smell this lesson started with.

Python: duck typing and protocols

Python does not need an interface for polymorphism. Any object with an area() method works in total_area: "if it walks like a duck and quacks like a duck". That is duck typing. To document the promise and let a type checker (mypy, Pyright) verify it, use an ABC (classes must inherit it, and Python refuses to create an object that is missing an abstract method) or a typing.Protocol (structural: any class with matching methods qualifies, no inheritance needed). @runtime_checkable lets isinstance check a protocol, but it only checks that the method names exist, not their signatures.

Program to an interface

Declare the interface, construct the implementation

  1. This is the habit called program to an interface: write Shape s = new Circle(2), and the rest of your code only ever relies on “it’s some Shape”. You already use it: Java’s List list = new ArrayList() is exactly this.

Write List<Order> orders = new ArrayList<>(), not ArrayList<Order> orders. Accept Shape parameters, not Circle. Then swapping the implementation (a LinkedList, a database-backed repository, a test fake) touches one line. This is the habit that dependency inversion builds on.

When not to use it

  • Two cases that will never grow. An if on a boolean is clearer than an interface with two implementations.
  • One implementation, no tests that need a fake. An interface with exactly one class "for flexibility" is ceremony; extract it when the second implementation (or a test double) actually appears.
  • The operations change more than the types. See the expression problem above: a sealed type with exhaustive switch can be the better fit.

In the interview

Your turn: report exporters

A reporting tool exports the same Report as CSV, JSON or PDF, and a fourth format is planned. PDF export needs a font file; the others need nothing. Design the types and the call site, in Java and Python.

Compare with our answer
interface Exporter {
    byte[] export(Report report);
    String fileExtension();
}

class CsvExporter implements Exporter {
    public byte[] export(Report r) { return r.rowsAsCsv().getBytes(java.nio.charset.StandardCharsets.UTF_8); }
    public String fileExtension() { return "csv"; }
}

class PdfExporter implements Exporter {
    private final java.nio.file.Path fontFile;          // config only PDF needs
    PdfExporter(java.nio.file.Path fontFile) { this.fontFile = fontFile; }
    public byte[] export(Report r) { /* lay out pages using fontFile */ return new byte[0]; }
    public String fileExtension() { return "pdf"; }
}

// call site: depends only on the interface
void save(Report r, Exporter e, java.nio.file.Path dir) throws java.io.IOException {
    java.nio.file.Files.write(dir.resolve(r.name() + "." + e.fileExtension()), e.export(r));
}

A strong answer mentions: one Exporter interface · one class per format · format-specific configuration (the font) in that class's constructor, not the interface · a call site that never checks the format · choosing the exporter in one place (a map or factory) · a new format being one new class.

Your turn: spot the bug

This Point has an equals method, yet Set.of(new Point(1, 2)).contains(new Point(1, 2)) is false. Why? Fix it, and give the Python equivalent.

class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    public boolean equals(Point p) { return p != null && x == p.x && y == p.y; }
}
Compare with our answer

equals(Point) overloads equals(Object); it does not override it. Collections call equals(Object), which still compares identity. There is also no hashCode, so hash-based sets look in the wrong bucket anyway.

import java.util.Objects;

final class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Point p && x == p.x && y == p.y;
    }

    @Override
    public int hashCode() { return Objects.hash(x, y); }
}
// or simply: record Point(int x, int y) { }

A strong answer mentions: overloading versus overriding · collections calling equals(Object) · @Override catching the mistake at compile time · overriding hashCode with equals · records or frozen dataclasses doing both for you.

Polymorphism on one page
  • Interface = a promise of methods; polymorphism = one call, behaviour chosen by the real object.
  • Static type decides what you may call; run-time type decides what runs (dynamic dispatch).
  • Override = same signature in a subclass, chosen at run time. Overload = same name, different parameters, chosen at compile time by declared types.
  • Replace conditionals with polymorphism: no instanceof chains on concrete classes.
  • Interface vs abstract class: many vs one; no state vs state and constructors; "can do" vs "is a kind of".
  • Python: duck typing; ABC (nominal) or Protocol (structural) to document and check the promise.
  • Program to an interface: declare List, construct ArrayList.
  • Blind spot: new operations touch every class; sealed types + exhaustive switch, or Visitor.
Interactive labPractise it: plug any appliance into one socketOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Shape s = new Circle(2); s.area(); Which area() runs, and when is that decided?

2. A Java class has log(Object o) and log(String s). What does Object msg = "hi"; log(msg); call?

3. A payment service has instanceof Card, instanceof Wallet and instanceof Upi checks in five places. A new method, BankTransfer, is coming. What is the best refactor?

4. Your team needs Flyable behaviour for Bird, Drone and Plane, which share nothing else. Which should Flyable be?

5. In Java, which can an abstract class do that an interface cannot?

6. A team keeps adding new operations on a fixed set of five shape types (export to SVG, to PDF, hit-testing, snapping) far more often than new shapes. What fits best?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.