Java Reference
In-Depth Information
This all works fine, except for one problem: This only makes sense if the type
plugged in for the type parameter
T
satisfies the
Comparable
interface, but Java allows
you to plug in any type for the type parameter
T
.
You can have Java enforce this restriction on the possible types that can be plugged
in for
T
. To ensure that only classes that implement the
Comparable
interface are
plugged in for
T
, you begin the class definition as follows:
public class
Pair<T
extends
Comparable>
The part
extends
Comparable
is called a
bound
on the type parameter
T
. If you
attempt to plug in a type for
T
which does not implement the
Comparable
interface,
you will get a compiler error message. Note that you use the keyword
extends
, not the
keyword
implements
as you would naturally expect.
Note that the bound
extends
Comparable
is not just an optional little nicety. If you
omit it, you will get an error message from the compiler saying it does not know about
the method
compareTo
.
This version of the generic class
Pair
with the method
max
is summarized in Dis-
play 14.10. On the accompanying CD, this version of
Pair
is in a subdirectory named
Bounded
Pair
.
A bound on a type may be a class name (rather than an interface name) in which
case only descendent classes of the bounding class may be plugged in for the type
parameters. For example, the following says that only descendent classes of the class
Employee
may be plugged in for
T
, where
Employee
is some class:
extends
bound
public class
SameGenericClass<T
extends
Employee>
Display 14.10
A Bounded Type Parameter
1
public class
Pair<T
extends
Comparable>
2{
3
private
T first;
4
private
T second;
5
public
T max()
6
{
7
if
(first.compareTo(second) <= 0)
8
return
first;
9
else
10
return
second;
11
}
<
All the constructors and methods given in Display 14.5
are also included as part of this generic class definition
>
12
}