Java Reference
In-Depth Information
[2]
You'll see a little later (page
258
) that it's better to actually declare this slightly differently, but for now
we keep it simple.
interface SortedCollection<E extends Comparable<E>> {
// ... sorted collection methods ...
}
Here
E
is restricted to be a type that "extends"
Comparable<E>
so that you
know that no matter what type argument is supplied, it is guaranteed
to support the methods of the
Comparable
interface. We say that
Compar-
able
is the
upper bound
on the type of
E
, and that
E
is a
bounded
type
parameter. The keyword
extends
is used here in a very general way to
mean either "extends" or "implements," depending on whether the type
that follows is a class type or an interface type. Any given class can ex-
tend only one other class, but multiple interfaces can be implemented
by classes or interfaces. A type bound can express such multiple de-
pendencies by declaring that the type parameter extends one class or
interface, followed by an ampersand (
&
) separated list of additional in-
terfaces that must be implemented. For example, a sorted collection of
character sequences could be declared as follows:
interface SortedCharSeqCollection<E extends Comparable<E>
& CharSequence> {
// ... sorted char sequence collection methods ...
}
Such a collection could hold
String
objects, for example.
11.1.2. Nested Generic Types
A nested type can also be declared as a generic type with its own type
variables. Because static members cannot refer to type variables of their
own class, any type variable in a static nested type is distinct from any
type variable in the outer type, even if they have the same name. For