Learn/Java/14. Interfaces and generics
Lesson 14 of 15
Sign in

Java, lesson 14

Interfaces and generics

Two features shape almost every Java library you will use. Interfaces let different classes promise the same abilities, so code can work with any of them. Generics let one class or method work safely with many element types. You have used both already: List<String> is a generic interface, and Comparator is an interface.

Interfaces: a contract

An interface lists methods a type promises to provide, without (usually) saying how:

Now code can work with any shape:

That is polymorphism: one variable type (Shape), many behaviours. The loop does not care what kind of shape it has, and you can add a Triangle later without touching it. Methods that implement an interface method must be public. A class can implement many interfaces, but extend only one class.

2 exercises to try what you just read.

Exercise 1

Shape report

Press Ctrl Enter or Check to test your code.

Exercise 2

Generic range

Press Ctrl Enter or Check to test your code.

Sealed interfaces and pattern matching

Sometimes you want a closed set of types. A sealed interface lists exactly which types may implement it, and a switch can then check every case:

The second case is a record pattern: it checks the type and unpacks the fields in one go. Because the interface is sealed, the compiler knows these cases are complete, so no default is needed, and it will complain if you add a new payment type and forget to handle it.

Generics: types as parameters

A generic class has a type parameter in angle brackets, conventionally a single capital letter (T for type, E for element, K/V for key and value):

A generic method declares its type parameter before the return type:

Often you need to know something about T. A bounded type parameter says "any T, as long as it can be compared with other Ts":

One method, written once, works for numbers, strings, dates and your own Comparable types, and the compiler still rejects nonsense like mixing strings and numbers in one call.

Further reading

  • Interfaces (dev.java)
  • Introducing generics (dev.java)
  • Pattern matching (dev.java)
  • Comparable API

The starter defines a Shape interface and one implementation, Circle. Add two more records that implement Shape: Square(double side) and Rect(double width, double height), and teach parse to create them.

Each input line is circle r, square s or rect w h. There is at least one line. For every shape, print <name>: <area> with two decimals, using the shape's name(). Then print the total area and the name of the largest shape (the first one, if several tie).

Sample input:

Sample output:

Write one generic method, static <T extends Comparable<T>> Pair<T, T> range(List<T> items), that returns a Pair holding the smallest and the largest item of a non-empty list. Use it twice: once for numbers and once for words.

The first input line holds whole numbers separated by spaces, the second line holds words. Both have at least one item. Print Numbers: <min> to <max> and Words: <min> to <max> (words compare alphabetically, case sensitive).

Sample input:

Sample output:

interface Shape {
    double area();                   // abstract: every shape must implement it

    default String describe() {      // default: shared code, can be overridden
        return String.format("%s with area %.2f", getClass().getSimpleName(), area());
    }
}

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

record Square(double side) implements Shape {
    public double area() { return side * side; }
}
List<Shape> shapes = List.of(new Circle(1), new Square(2));
double total = 0;
for (Shape s : shapes) {
    total += s.area();               // calls the right area() for each object
}
sealed interface Payment permits Cash, Card { }
record Cash(double amount) implements Payment { }
record Card(double amount, String last4) implements Payment { }

static String receipt(Payment p) {
    return switch (p) {
        case Cash c -> "Cash " + c.amount();
        case Card(double amount, String last4) -> "Card *" + last4 + " " + amount;
    };
}
record Pair<A, B>(A first, B second) { }

Pair<String, Integer> entry = new Pair<>("apples", 3);
String name = entry.first();      // no cast needed: the compiler knows it is a String
static <T> T lastOf(List<T> items) {
    return items.get(items.size() - 1);
}
static <T extends Comparable<T>> T maxOf(List<T> items) {
    T best = items.get(0);
    for (T item : items) {
        if (item.compareTo(best) > 0) best = item;
    }
    return best;
}

maxOf(List.of(3, 9, 4));            // 9
maxOf(List.of("kiwi", "apple"));    // kiwi
circle 1
square 2
rect 2 3
Circle: 3.14
Square: 4.00
Rect: 6.00
Total: 13.14
Largest: Rect
17 3 42 8
pear apple plum
Numbers: 3 to 42
Words: apple to plum