Multiple Bounds
A bounded type parameter can have multiple bounds, B1 & B2 & … & Bn, which must be satisfied by the actual type parameter:
class CmpNode<E extends Number & Serializable> …
An extra bound, the Serializable interface, has been added using the ampersand (&). The formal type parameter E is a subtype of both Number and Serializable, and represents both of these concrete types in the body of the generic class. The constraint above will only allow the generic type to be parameterized by an actual type parameter which is a subtype of both Number and Serializable.
We can add as many bounds as necessary. A type parameter E having multiple bounds is a subtype of all of the types denoted by the individual bounds. A bound can be a parameterized type, as in the following generic class header:
class CmpNode<E extends Comparable<E> & Serializable> …
If the raw type of a bound is a (non-final) superclass of the bounded type parameter, it can only be specified as the first bound, and there can only be one such bound (as a subclass can only extend one immediate superclass). The raw type of an individual bound cannot be used with different type arguments, since a type parameter cannot be the subtype of more than one bound having the same raw type. In the class header below, whatever E is, it cannot be a subtype of two parameterizations of the same interface type (i.e., Comparable) at the same time:
class CmpNode<E extends Comparable<E> & Serializable & Comparable<String>> //Error
If the type parameter has a bound, methods of the bound can be invoked on instances of the type parameter in the generic class. Otherwise, only methods from the Object class can be invoked on instances of the type parameter. In the declaration of the generic class Node<E> in Example 11.2, p. 568, we cannot call any methods on instances of the type parameter except for those in the Object class because the type parameter is unbounded. Since the instances of the type parameter E are guaranteed to be Comparable<E> in the generic class CmpNode, we can call the method com-pareTo() of the Comparable interface on these instances.
Leave a Reply