Java Reference ยท Object-Oriented Concepts
Bounded type parameters in Java
Reference for Java bounded type parameters: upper bounds with extends, multiple bounds with &, recursive bounds like T extends Comparable<T>, and erasure effects.
A bounded type parameter limits which types may be used as an argument. In <T extends Number>, T can be Number or any subclass such as Integer or Double. The bound tells the compiler what T can do, so inside the method you may call Number methods on a T value. Without a bound, T is only known to be an Object.
Java supports only upper bounds on type parameters (extends). The keyword is extends even when the bound is an interface. Lower bounds (super) exist only for wildcards, not for named type parameters.
static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
<T extends Bound> <T extends Bound1 & Bound2 & Bound3> <T extends Comparable<T>> // recursive (self-referential) bound
| Rule | Detail |
|---|---|
| Keyword | extends for both classes and interfaces. |
| Multiple bounds | Joined with &. At most one class, and it must come first. |
| Allowed in | Class, interface, method and constructor type parameters. |
| Recursive bound | T extends Comparable<T> means T can compare to itself. |
| Lower bound | Not available on type parameters; use ? super T on wildcards. |
Usage notes
- Why bound? It lets you call the bound's methods on
T.<T extends Comparable<T>>makesa.compareTo(b)legal. Comparable<? super T>is the more general form used byCollections.sort; it accepts a class whosecompareTois inherited from a superclass, such asjava.sql.Timestampandjava.util.Date.- Erasure: a type variable erases to its first bound, so
T extends Number & Comparable<T>erases toNumber, and the compiler inserts casts toComparablewhere needed. Put the most commonly used type first if binary compatibility matters. - Bound or wildcard? For a parameter you only read,
List<? extends Number>is simpler. Use a named bounded parameter when the type appears more than once (for example in the return type or two parameters). - Enum helpers:
<E extends Enum<E>>is the standard shape for methods over any enum, used byEnumSetandEnum.valueOf. - Compile errors such as "type argument is not within bounds" mean the actual type does not satisfy every bound.
- Final classes as bounds are legal but pointless, as there is only one possible type.