Skip to content
LumenaryAcademy
Foundations 60 min

Interfaces, inheritance and generics

Programming to what things can do rather than what they are, and writing code that works for many types without giving up type safety.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Code that does not care what it is given

A bus company in Nairobi charges a flat fare on some routes and a distance-based fare on others, offers a student fare, and is planning a peak-hour surcharge. Somewhere in its software, a method prints a ticket. Should that method contain an if for every kind of fare, to be edited each time the marketing team has an idea?

It should not. The ticket printer needs exactly one thing from a fare: given a distance, what is the price? If the language lets us name that capability, the printer can be written once against the name, and every fare, including ones invented next year, can plug in. In Java that name is an interface, and the mechanism that calls the right code for each kind of fare is dynamic dispatch.

A second problem has the same flavour. A method that finds the largest element of a list should work for numbers, for strings, for dates, for anything that can be compared, without being copied for each type and without losing the compiler's checks. That is what generics are for.

Interfaces and generics are how large Java systems stay flexible without becoming fragile. Every framework you will use (collections, streams, Spring, JUnit) is built from them, so reading them fluently matters as much as writing them.

DefinitionsH

Definitions

Definition— Interface

A type that declares what its implementations can do, mostly as abstract methods (a signature with no body). A class that says implements Fare must provide a body for each. Since Java 8 interfaces may also have default methods (with a body that implementations inherit or override) and static methods; since Java 9, private helper methods.

Definition— Functional interface and lambda

An interface with exactly one abstract method. Any functional interface can be implemented by a lambda expression, such as km -> 50, or a method reference, such as String::length. The package java.util.function provides standard ones: Function, Predicate, Supplier, Consumer, UnaryOperator, BiFunction and their relatives.

Definition— Inheritance and overriding

A class may extends exactly one superclass, inheriting its fields and methods. A subclass overrides an inherited instance method by declaring one with the same signature. Every class ultimately extends Object. An abstract class cannot be instantiated and may declare abstract methods for its subclasses to fill in.

Definition— Dynamic dispatch

When an instance method is called, the JVM chooses the implementation by the run-time class of the object, not by the declared type of the variable. This is what makes one call site behave differently for different objects (polymorphism). Static methods are not dispatched this way.

Definition— Generic type, type parameter and type argument

A class, interface or method declared with type parameters, such as Pair with A and B. Using it supplies type arguments, as in Pair<String, Integer>. The compiler checks every use against the arguments, so a List<String> can only ever contain strings.

Worked examplesH

An interface, two classes and a lambda

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

/** How much a bus ride costs, in cents, for a trip of a given length. */
interface Fare {
    long priceCents(int km);

    default String describe(int km) {             // a default method: inherited unless overridden
        return "%d km costs %d.%02d".formatted(km, priceCents(km) / 100, priceCents(km) % 100);
    }

    static Fare cheapest(List<Fare> fares, int km) {   // a static method on the interface
        Fare best = fares.getFirst();
        for (Fare f : fares) {
            if (f.priceCents(km) < best.priceCents(km)) {
                best = f;
            }
        }
        return best;
    }
}

class FlatFare implements Fare {
    private final long cents;

    FlatFare(long cents) {
        this.cents = cents;
    }

    @Override
    public long priceCents(int km) {
        return cents;
    }

    @Override
    public String toString() {
        return "flat " + cents;
    }
}

class DistanceFare implements Fare {
    private final long base;
    private final long perKm;

    DistanceFare(long base, long perKm) {
        this.base = base;
        this.perKm = perKm;
    }

    @Override
    public long priceCents(int km) {
        return base + perKm * km;
    }

    @Override
    public String toString() {
        return "distance " + base + "+" + perKm + "/km";
    }
}

public class Main {
    public static void main(String[] args) {
        Fare student = km -> 50;                       // a lambda implements a one-method interface
        List<Fare> fares = new ArrayList<>(List.of(new FlatFare(250), new DistanceFare(100, 20)));

        for (Fare f : fares) {
            System.out.println(f + ": " + f.describe(4) + ", " + f.describe(12));
        }
        System.out.println("student: " + student.describe(30));
        System.out.println("cheapest for 4 km:  " + Fare.cheapest(fares, 4));
        System.out.println("cheapest for 12 km: " + Fare.cheapest(fares, 12));
    }
}
text
flat 250: 4 km costs 2.50, 12 km costs 2.50
distance 100+20/km: 4 km costs 1.80, 12 km costs 3.40
student: 30 km costs 0.50
cheapest for 4 km:  distance 100+20/km
cheapest for 12 km: flat 250

Look at what describe and cheapest do not contain: any mention of FlatFare or DistanceFare. They are written against the interface, and the call priceCents(km) is dispatched at run time to whichever class the object belongs to. Adding a PeakFare class tomorrow requires no change to either method. That is the open–closed idea: open to extension, closed to modification.

A few details:

  • Interface methods are implicitly public and abstract, so implementations must declare them public. Forgetting public is a compile error ("attempting to assign weaker access privileges").
  • describe is a default method. Both classes inherit it; either could override it. Default methods were added in Java 8 so that interfaces such as List could gain new methods without breaking every class that already implemented them.
  • Fare has exactly one abstract method, so it is a functional interface and km -> 50 is a complete implementation. The parameter type of km is inferred from the interface. Adding @FunctionalInterface above the interface would ask the compiler to keep it that way.
  • new ArrayList<>(...) uses the diamond: the compiler infers the type argument from the variable's declared type.
  • fares.getFirst() comes from sequenced collections (JDK 21); before that you would write fares.get(0).
Worked examplesH

Inheritance and abstract classes

Interfaces share a contract; inheritance shares implementation. An abstract class is the right tool when several classes share both state and an algorithm, and differ in a few steps:

java
import java.util.List;

abstract class Sensor {
    private final String id;

    protected Sensor(String id) {
        this.id = id;
    }

    protected abstract double measure();     // each kind of sensor measures differently
    protected abstract String unit();

    // The shared algorithm, written once; final so subclasses cannot change it
    public final String report() {
        return id + ": " + measure() + " " + unit();
    }
}

class Thermometer extends Sensor {
    private final double celsius;

    Thermometer(String id, double celsius) {
        super(id);                             // run the superclass constructor first
        this.celsius = celsius;
    }

    @Override
    protected double measure() {
        return celsius;
    }

    @Override
    protected String unit() {
        return "C";
    }
}

class RainGauge extends Sensor {
    private final double millimetres;

    RainGauge(String id, double millimetres) {
        super(id);
        this.millimetres = millimetres;
    }

    @Override
    protected double measure() {
        return millimetres;
    }

    @Override
    protected String unit() {
        return "mm";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Sensor> station = List.of(
                new Thermometer("T-01", 31.5),
                new RainGauge("R-07", 12.0),
                new Thermometer("T-02", 29.0));

        for (Sensor s : station) {
            System.out.println(s.report());       // dynamic dispatch picks each subclass's measure()
        }

        Sensor first = station.get(0);
        System.out.println(first instanceof Thermometer);
        System.out.println(first instanceof RainGauge);
        System.out.println(first.getClass().getSimpleName() + " extends " + first.getClass().getSuperclass().getSimpleName());
    }
}
text
T-01: 31.5 C
R-07: 12.0 mm
T-02: 29.0 C
true
false
Thermometer extends Sensor

report() is a template method: the superclass fixes the shape of the algorithm and calls abstract "hooks" that subclasses supply. Marking it final stops a subclass from overriding the shared part by accident. super(id) calls the superclass constructor, which always runs before the subclass's fields are set (you may put validation before it since JDK 25, but not code that uses this). protected makes the hooks visible to subclasses without making them part of the public interface.

instanceof asks about the run-time class, and getClass() returns it. Notice that the program never needs instanceof to print the reports; dynamic dispatch does that work. A long chain of if (s instanceof Thermometer) ... else if (s instanceof RainGauge) ... is usually a sign that a method belongs on the type itself. (Java 21's pattern matching makes such checks safe and neat when they are the right design, especially with sealed types; see Records, sealed types and pattern matching.)

Composition over inheritance

Inheritance couples a subclass tightly to its superclass's implementation. If the superclass changes how its methods call each other, subclasses that override some of them can break, even though nothing in their own code changed. This "fragile base class" problem is why experienced Java developers:

  • use inheritance only for genuine "is a kind of" relationships within code they control, ideally with abstract classes designed for it;
  • otherwise compose: give a class a field holding another object and delegate to it. A LoggingFare that has a Fare and adds logging around priceCents works with every fare, present and future, which a subclass of DistanceFare never could;
  • make classes final (or, from JDK 17, sealed) when they are not designed to be extended.

Java allows a class to extend one class but implement many interfaces, so interfaces are also the only way to say that one object plays several roles.

Worked examplesH

Generics: one piece of code, many types

Before Java 5, a List held plain Objects; you cast each element when you took it out and hoped. Generics moved that check to compile time. Here are generic classes, generic methods, bounds and wildcards in one program:

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

/** An immutable pair of two values of possibly different types. */
class Pair<A, B> {
    private final A first;
    private final B second;

    Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    A first() { return first; }
    B second() { return second; }

    <C> Pair<A, C> withSecond(C newSecond) {          // a generic method with its own type parameter
        return new Pair<>(first, newSecond);
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ")";
    }
}

public class Main {
    // A bounded type parameter: T must be comparable with itself (or a supertype)
    static <T extends Comparable<? super T>> T largest(List<T> items) {
        T best = items.getFirst();
        for (T item : items) {
            if (item.compareTo(best) > 0) {
                best = item;
            }
        }
        return best;
    }

    // "? extends Number": we only read from the list, so any list of a Number subtype will do
    static double total(List<? extends Number> numbers) {
        double sum = 0;
        for (Number n : numbers) {
            sum += n.doubleValue();
        }
        return sum;
    }

    // "? super Integer": we only add Integers, so a list of Integer, Number or Object will do
    static void addCountdown(List<? super Integer> target) {
        for (int i = 3; i >= 1; i--) {
            target.add(i);
        }
    }

    public static void main(String[] args) {
        Pair<String, Integer> city = new Pair<>("Nairobi", 1795);
        Pair<String, Double> rounded = city.withSecond(1.8);
        System.out.println(city + " " + rounded);

        System.out.println(largest(List.of(4, 17, 9)));
        System.out.println(largest(List.of("pear", "apple", "quince")));

        System.out.println(total(List.of(1, 2, 3)) + total(List.of(0.5, 0.25)));

        List<Number> mixed = new ArrayList<>(List.of(2.5));
        addCountdown(mixed);
        System.out.println(mixed);

        // Type arguments are erased at run time: both lists have the same class
        List<String> words = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        System.out.println(words.getClass() == counts.getClass());

        // Arrays are covariant and checked at run time; generic lists are not covariant at all
        Object[] things = new String[2];
        try {
            things[0] = 42;
        } catch (ArrayStoreException e) {
            System.out.println("ArrayStoreException: " + e.getMessage());
        }
    }
}
text
(Nairobi, 1795) (Nairobi, 1.8)
17
quince
6.75
[2.5, 3, 2, 1]
true
ArrayStoreException: java.lang.Integer

(The pair holds Nairobi's elevation: about 1,795 metres, or 1.8 kilometres.)

Generic classes and methods. Pair has two type parameters, so Pair<String, Integer> and Pair<String, Double> are different types and the compiler tracks which is which. withSecond declares its own type parameter C before its return type; calls rarely spell it out, because the compiler infers it from the argument.

Bounds. largest needs to call compareTo, so it cannot accept any T whatsoever. The bound T extends Comparable<? super T> says "T must be comparable with T, or with some supertype of T". Integers and strings both qualify; their natural orders give 17 and "quince" (alphabetical). Read extends in a bound as "is a subtype of", whether the bound is a class or an interface.

Invariance and wildcards. Here is the rule that surprises everyone once: List<Integer> is not a subtype of List<Number>, even though Integer is a subtype of Number. If it were, you could pass a list of integers to a method expecting numbers, and that method could legally add a Double to it, corrupting the caller's list. So generic types are invariant, and wildcards express the safe exceptions:

  • List<? extends Number> accepts a list of Number or any subtype. You can read Numbers from it, but you cannot add to it (except null), because you do not know the exact element type. total only reads, so it accepts both List<Integer> and List<Double>.
  • List<? super Integer> accepts a list of Integer or any supertype. You can add Integers to it, but reading gives you only Object. addCountdown only adds, so it accepts the List<Number>.

Joshua Bloch's mnemonic for this is PECS: producer extends, consumer super. If a parameter produces values for you, use extends; if it consumes values you give it, use super; if both, use the exact type. You will see these wildcards all over the standard library's signatures, such as Collections.sort and Comparator.comparing.

Arrays are different. Arrays are covariant: a String[] can be assigned to an Object[] variable. To stay safe, every array store is checked at run time, and putting an Integer into what is really a String[] throws ArrayStoreException. Generics chose compile-time safety instead. This is one reason professionals prefer List to arrays in most code.

ExplanationH

Type erasure, and why it matters

Generics were added to Java in 2004, to a platform with millions of existing programs and libraries. To stay compatible, the designers implemented them by erasure: the compiler checks type arguments and then removes them, inserting casts where needed. At run time a List<String> and a List<Integer> are both plain ArrayList objects, which is why the program above printed true.

Erasure has consequences you will meet in real code. Inside a class with a type parameter T, the compiler rejects all of these:

java
T make()            { return new T(); }        // error: unexpected type
T[] many()          { return new T[10]; }      // error: generic array creation
boolean is(Object o) { return o instanceof T; } // error: Object cannot be safely cast to T

The usual workarounds are to pass in what the run time cannot know: a Supplier (() -> new Thing()) to create objects, a Class object to check types, or a List instead of an array. Frameworks that need full type information at run time, such as JSON libraries, recover it with tricks built on reflection. Erasure was a compromise, and an honest one; it is why a library compiled for Java 1.4 could run unchanged next to generic code. (Kotlin, which compiles to the same bytecode, inherits erasure too, and offers "reified" type parameters in inline functions as a partial escape.)

Two habits keep generic code healthy. First, never use a raw type (plain List with no type argument) in new code; it switches off the checks and exists only for compatibility. Second, take compiler "unchecked" warnings seriously; each is a place where the compile-time guarantee has a hole.

Common misconceptionsH

Common misconceptions

Misconception

"Interfaces cannot contain code." Since Java 8 they can have default and static methods, and since Java 9 private methods. They still cannot have instance fields; state belongs in classes.

Misconception

"Inheritance is the way to reuse code." It is one way, and often not the best. Composition and delegation reuse code without coupling the reuser to another class's internals. Reach for inheritance when there is a genuine "is a kind of" relationship and the superclass was designed to be extended.

Misconception

"List<Integer> can be passed where List<Number> is expected." Generic types are invariant. Declare the parameter as List<? extends Number> if you only read from it.

Misconception

"Static methods can be overridden." A static method in a subclass with the same signature hides the superclass's method; calls are resolved by the declared type at compile time, not dispatched at run time. Call static methods through the class name to avoid confusion.

Exercises

Exercises

1. Interfaces, inheritance and generics

Warm-upComputational

What does this program print?

class Animal {
    String sound() { return "..."; }
    String speak() { return "I say " + sound(); }
}

class Dog extends Animal {
    @Override
    String sound() { return "woof"; }
}

void main() {
    Animal a = new Dog();
    IO.println(a.speak());
}

2. Interfaces, inheritance and generics

StretchComputational

What does this program print? (It compiles, with a warning about calling a static method through an instance.)

class A {
    static String who() { return "A"; }
    String me() { return "A"; }
}

class B extends A {
    static String who() { return "B"; }
    @Override
    String me() { return "B"; }
}

void main() {
    A x = new B();
    IO.println(x.who() + x.me());
}

3. Interfaces, inheritance and generics

CoreComputational

Op is a functional interface with a default method. What does this program print?

interface Op {
    int apply(int x);

    default Op twice() {
        return x -> apply(apply(x));
    }
}

void main() {
    Op inc = x -> x + 3;
    IO.println(inc.twice().twice().apply(1));
}

4. Interfaces, inheritance and generics

CoreHuman

Given static double total(List<? extends Number> numbers), which arguments compile? Choose all that apply.

Choose all that apply

5. Interfaces, inheritance and generics

CoreHuman

You are writing static void fillWithZeros(List<___> target, int n), which adds n Integer zeros to target. Which declaration lets callers pass a List<Integer>, a List<Number> or a List<Object>?

Choose one

6. Interfaces, inheritance and generics

StretchHuman

Inside class Holder<T>, which of these does the compiler reject because of type erasure? Choose all that apply.

Choose all that apply

Further reading and resources