Java Reference
In-Depth Information
Type variables can be constrained with bounds.
The Comparable bound is necessary for calling the compareTo method. Had it
been omitted, then the min method would not have compiled. It would have been
illegal to call compareTo on a[i] if nothing is known about its type. (Actually, the
Comparable interface is itself a generic type, but for simplicity we do not supply a
type parameter. See Advanced Topic 17.1 for more information.)
Very occasionally, you need to supply two or more type bounds. Then you separate
them with the & character, for example
<E extends Comparable & Cloneable >
The extends keyword, when applied to type variables, actually means È’extends or
implementsȓ. The bounds can be either classes or interfaces, and the type variable can
be replaced with a class or interface type.
S ELF C HECK
7. How would you constrain the type variable for a generic
BinarySearchTree class?
8. Modify the min method to compute the minimum of an array of
elements that implements the Measurable interface of Chapter 9 .
778
779
C OMMON E RROR 17.1: Genericity and Inheritance
If SavingsAccount is a subclass of BankAccount , is
ArrayList<SavingsAccount> a subclass of
ArrayList<BankAccount> ? Perhaps surprisingly, it is not. Inheritance of
type parameters does not lead to inheritance of generic classes. There is no
relationship between ArrayList<SavingsAccount> and
ArrayList<BankAccount> .
This restriction is necessary for type checking. Suppose it was possible to assign
an ArrayList<SavingsAccount> object to a variable of type
ArrayList<BankAccount> :
Search WWH ::




Custom Search