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.
On this page
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
- 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
- An interface is a promise. “Anything that implements Shape must have an area() method.” It says what a class can do, not how.
- 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) type | Run-time (actual) type | |
|---|---|---|
In Shape s = new Circle(2); | Shape | Circle |
| Decided | When the code compiles | When the object is created |
| Controls | Which methods you are allowed to call | Which 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
}
}import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
def describe(self) -> str: # shared code in the base
return f"{type(self).__name__} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, radius: float):
self.radius = radius
def area(self) -> float:
return math.pi * self.radius ** 2
class Rect(Shape):
def __init__(self, width: float, height: float):
self.width, self.height = width, height
def area(self) -> float:
return self.width * self.height
class Triangle(Shape):
def __init__(self, a: float, b: float, c: float):
if a + b <= c or a + c <= b or b + c <= a:
raise ValueError("not a triangle")
self.a, self.b, self.c = a, b, c
def area(self) -> float: # Heron's formula
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def total_area(shapes: list[Shape]) -> float:
return sum(s.area() for s in shapes) # no isinstance: each object answers
if __name__ == "__main__":
shapes = [Circle(1), Rect(2, 3), Triangle(3, 4, 5)]
for s in shapes:
print(s.describe())
print(f"total {total_area(shapes):.2f}") # total 15.14Adding 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
- 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.
| Overriding | Overloading | |
|---|---|---|
| What | Subclass replaces a method with the same signature | Same class has methods with the same name, different parameters |
| Chosen | At run time, by the object's actual class | At compile time, by the arguments' declared types |
| Example | Circle.area() overrides Shape.area() | print(int), print(String) |
| Python | Yes | No: 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.
| Interface | Abstract class | |
|---|---|---|
| A class can have | Many (implements A, B, C) | One (extends Base) |
| Instance fields (state) | No (constants only) | Yes |
| Constructors | No | Yes, to set up shared state |
| Method bodies | default and static (Java 8+), private (Java 9+) | Any |
| Expresses | "can do": a capability | "is a kind of", with shared state and steps |
| Use when | Unrelated classes should be usable the same way | Closely 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());
}
}
}from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable
@runtime_checkable
class Refundable(Protocol): # a capability only some methods have
def refund(self, cents: int) -> None: ...
class PaymentMethod(ABC):
def __init__(self):
self._log: list[str] = [] # shared state
def pay(self, cents: int) -> None: # shared steps
if cents <= 0:
raise ValueError("amount must be positive")
self._charge(cents) # dynamic dispatch to the subclass
self._log.append(f"{self.name()} charged {cents}")
@abstractmethod
def _charge(self, cents: int) -> None: ...
@abstractmethod
def name(self) -> str: ...
def log(self) -> list[str]:
return list(self._log)
class Card(PaymentMethod):
def _charge(self, cents): print(f"card network: {cents}")
def name(self): return "card"
def refund(self, cents): print(f"card refund: {cents}")
class GiftVoucher(PaymentMethod): # vouchers cannot be refunded
def __init__(self, remaining: int):
super().__init__()
self._remaining = remaining
def _charge(self, cents):
if cents > self._remaining:
raise RuntimeError("voucher too small")
self._remaining -= cents
def name(self): return "voucher"
if __name__ == "__main__":
for m in [Card(), GiftVoucher(5_000)]:
m.pay(1_500)
if isinstance(m, Refundable): # structural check: has a refund method
m.refund(500)
print(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
- 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
ifon 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
switchcan be the better fit.
In the interview
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));
}from abc import ABC, abstractmethod
from pathlib import Path
class Exporter(ABC):
@abstractmethod
def export(self, report) -> bytes: ...
@abstractmethod
def file_extension(self) -> str: ...
class CsvExporter(Exporter):
def export(self, report): return report.rows_as_csv().encode("utf-8")
def file_extension(self): return "csv"
class PdfExporter(Exporter):
def __init__(self, font_file: Path):
self.font_file = font_file # config only PDF needs
def export(self, report): return b"" # lay out pages using font_file
def file_extension(self): return "pdf"
def save(report, exporter: Exporter, folder: Path) -> None:
(folder / f"{report.name}.{exporter.file_extension()}").write_bytes(exporter.export(report))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.
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) { }class Point:
def __init__(self, x: int, y: int):
self.x, self.y = x, y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self): # defining __eq__ sets __hash__ to None unless you add this
return hash((self.x, self.y))
# or simply: @dataclass(frozen=True) class Point: x: int; y: intA 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.
- 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
instanceofchains 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) orProtocol(structural) to document and check the promise. - Program to an interface: declare
List, constructArrayList. - Blind spot: new operations touch every class; sealed types + exhaustive
switch, or Visitor.
1. Shape s = new Circle(2); s.area(); Which area() runs, and when is that decided?
Overridden methods are dispatched on the run-time class. The declared type only decides which methods the compiler lets you call.
2. A Java class has log(Object o) and log(String s). What does Object msg = "hi"; log(msg); call?
Overload resolution uses static types. Only overriding is resolved at run time.
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?
Each class answering for itself removes all five chains; a new method is one new class. Centralising the checks in a helper is better than scattering them, but still needs editing for every new type.
4. Your team needs Flyable behaviour for Bird, Drone and Plane, which share nothing else. Which should Flyable be?
A capability across unrelated classes is exactly what interfaces are for. A class can extend only one abstract class, and Drone or Plane may already extend something else.
5. In Java, which can an abstract class do that an interface cannot?
Interfaces can have abstract, default, static and private methods, and can be used as types, but they cannot hold per-instance state or define constructors.
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?
Polymorphic methods make new types cheap but new operations expensive. When operations change more, keeping each operation in one place, checked for exhaustiveness by the compiler, is the better trade.
Score 60% or more and the lesson is marked complete.