return v;
}
}
class GenIFDemo {
public static void main(String args[]) {
Integer inums[] = {3, 6, 2, 8, 6 };
Character chs[] = {'b', 'r', 'p', 'w' };
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
}
}
The output is shown here:
Max
value
in
inums: 8
Min
value
in
inums: 2
Max
value
in
chs: w
Min
value
in
chs: b
Although most aspects of this program should be easy to understand, a couple of key
points need to be made. First, notice that MinMax is declared like this:
interface MinMax<T extends Comparable<T>> {
In general, a generic interface is declared in the same way as is a generic class. In this case,
the type parameter is T, and its upper bound is Comparable, which is an interface defined by
java.lang. A class that implements Comparable defines objects that can be ordered. Thus,
requiring an upper bound of Comparable ensures that MinMax can be used only with
objects that are capable of being compared. (See Chapter 16 for more information on
Comparable.) Notice that Comparable is also generic. (It was retrofitted for generics by
JDK 5.) It takes a type parameter that specifies the type of the objects being compared.
Next, MinMax is implemented by MyClass. Notice the declaration of MyClass,
shown here:
class MyClass<T extends Comparable<T>> implements MinMax<T> {
Pay special attention to the way that the type parameter T is declared by MyClass and
then passed to MinMax. Because MinMax requires a type that implements Comparable,
the implementing class (MyClass in this case) must specify the same bound. Furthermore,
once this bound has been established, there is no need to specify it again in the implements
clause. In fact, it would be wrong to do so. For example, this line is incorrect and won't compile:
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home