Skip to content

Type Bounds

The Course
•
15 min study

An unconstrained T provides only Object's operations. A bound narrows the allowed type arguments so generic code can call an agreed capability. Prefer a small interface capability to a cast that assumes every value has a particular implementation.

Work through the example

<T extends Named> means T must be Named or one of its implementing types. In a generic bound, extends is used for an interface too; class declarations still use implements. The bound lets firstTitle call title() while keeping T as the actual element type.

Use a bound only when the operation genuinely needs that capability. A generic copy method does not need Named; adding that constraint would unnecessarily exclude integers and other values. The signature should describe exactly the relationship the method uses.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = new ArrayList<>();
        tasks.add(new Task("Read"));
        System.out.println(firstTitle(tasks));
    }

    static <T extends Named> String firstTitle(List<T> values) {
        if (values.isEmpty()) {
            throw new IllegalArgumentException("nonempty list required");
        }
        return values.get(0).title();
    }
}

interface Named {
    String title();
}

final class Task implements Named {
    private final String title;

    Task(String title) {
        this.title = title;
    }

    public String title() {
        return title;
    }
}
Check your prediction
Text
Read

Compare the behavior

A type bound does not imply a nonnull value. The caller can still pass null unless you reject it. This example enforces the rule explicitly. It is a runtime value check, not something achieved by writing extends Named.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        System.out.println(show(new Label()));
        try {
            show(null);
        } catch (IllegalArgumentException error) {
            System.out.println(error.getMessage());
        }
    }

    static <T extends Named> String show(T value) {
        if (value == null) {
            throw new IllegalArgumentException("named value required");
        }
        return value.title();
    }
}

interface Named {
    String title();
}

final class Label implements Named {
    public String title() {
        return "Java";
    }
}
Check your prediction
Text
Java
named value required

Ask whether the type relationship needs a name

A bound says which operations generic code may rely on. Without a bound, T only supplies Object's operations. With T extends Named, code can call title without guessing an implementation or casting. The extends keyword in a type bound covers interfaces as well as classes.

However, a generic method is not always the simplest API. A method that accepts one Named value and returns a String could simply take Named. A method receiving List<Task> needs to account for the fact that List<Task> is not List<Named>; a bound or the wildcard introduced next can express that compatibility. Use the syntax to preserve an actual relationship, not as decoration.

A bound cannot prove the reference is nonnull or that a returned title has visible text. Those remain value-level promises. Test a second implementing class and the invalid reference policy so the implementation cannot silently depend on one concrete class.

Practice independently

Exercise

Type Bounds: practice

Here is a case where a bound is actually needed. Define a Sized interface with size(), and a Batch class implementing it that also has its own method, label(), which Sized does not have. Write a method largest that takes a nonempty list and returns its largest element with its own type, so the caller can call label() on the result without a cast:

Java
Batch biggest = largest(batches);
System.out.println(biggest.label());

Reject an empty list with nonempty list required. With batches of sizes 2, 5 and 3 labelled A, B and C:

Text
B
5
Your workspace Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println("Write a bounded largest method");
    }
}
Hint 1: the idea

The method needs two things at once: it must call size() on the elements, and it must return the same type it was given. A plain Sized parameter gives the first but loses the second; a plain T gives the second but not the first.

Hint 2: a first step

Write the loop body first with a Sized parameter and return type, and see that the caller can't assign the result to its own type without a cast. Then change the type parameter so it carries both facts, and only the signature changes.

Show one solution
Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Batch> batches = List.of(new Batch("A", 2), new Batch("B", 5), new Batch("C", 3));
        Batch biggest = largest(batches);
        System.out.println(biggest.label());
        System.out.println(biggest.size());
    }

    static <T extends Sized> T largest(List<T> items) {
        if (items.isEmpty()) {
            throw new IllegalArgumentException("nonempty list required");
        }
        T best = items.get(0);
        for (T item : items) {
            if (item.size() > best.size()) {
                best = item;
            }
        }
        return best;
    }
}

interface Sized {
    int size();
}

final class Batch implements Sized {
    private final String label;
    private final int size;

    Batch(String label, int size) {
        this.label = label;
        this.size = size;
    }

    public int size() {
        return size;
    }

    String label() {
        return label;
    }
}

Expected output:

Text
B
5

T extends Sized lets the body call item.size(); returning T (not Sized) means a List<Batch> gives back a Batch, so biggest.label() compiles. Both halves of the signature are doing work, which is the test for whether a bound is worth writing.

Change it and test again

Change only largest's return type from T to Sized. Which line of main stops compiling, and what would you need to write there instead? Restore the bound. Then compare with the Trace example above: show returns a String, so a plain Named parameter would do the same job there. Use the simpler signature when no type has to come back out.

Explain before moving on

When does a generic bound add useful information beyond an interface parameter? Avoid generic syntax that makes a straightforward method harder to read without improving its contract.

Was this article helpful?

Your response is saved on this device.