Java Reference
In-Depth Information
Recall that the method compareTo is required to be a member of any class that
implements the Comparable interface. The Comparable interface is a standard Java
interface that was discussed in Chapter 13 . Recall that the Comparable interface has
only the following method heading that must be implemented:
compareTo
public int compareTo(Object other);
When defining a class that implements the Comparable interface, the programmer is
expected to define compareTo so that it returns
a negative number if the calling object “comes before” the parameter other ,
a zero if the calling object “equals” the parameter other ,
and a positive number if the calling object “comes after” the parameter other .
This all works fine, except for one problem: This makes sense only 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 , 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 that 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
Display 14.10 . On the accompanying website, 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>
 
Search WWH ::




Custom Search