Bounded Type Parameters - RichardDanielOliva/java-learning-wiki GitHub Wiki
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type.
Bounded means “restricted“, we can restrict types that can be accepted by a method. For example,** we can specify that a method accepts a type and all its subclasses (upper bound) or a type all its superclasses (lower bound)**.
To declare an upper bounded (subclasses) type we use the keyword extends after the type followed by the upper bound that we want to use. For example:
public <T extends Number> List<T> fromArrayToList(T[] a) {
...
}
The keyword extends is used here to mean that the type T extends the upper bound in case of a class or implements an upper bound in case of an interface.
To declare an lower bound type (superclasses) we use the keyword super after the type
public <T super BigInteger> List<T> fromArrayToList(T[] a) {
...
}
Multiple Bounds
A type can also have multiple upper bounds as follows:
<T extends Number & Comparable>
If one of the types that are extended by T is a class (i.e Number), it must be put first in the list of bounds. Otherwise, it will cause a compile-time error.