img
test.showval();
test2.showval();
}
}
The output is shown here:
val: 100.0
val: 123.5
Because GenCons( ) specifies a parameter of a generic type, which must be a subclass of
Number, GenCons( ) can be called with any numeric type, including Integer, Float, or
Double. Therefore, even though GenCons is not a generic class, its constructor is generic.
Generic Interfaces
In addition to generic classes and methods, you can also have generic interfaces. Generic
interfaces are specified just like generic classes. Here is an example. It creates an interface
called MinMax that declares the methods min( ) and max( ), which are expected to return
the minimum and maximum value of some set of objects.
// A generic interface example.
// A Min/Max interface.
interface MinMax<T extends Comparable<T>> {
T min();
T max();
}
// Now, implement MinMax
class MyClass<T extends Comparable<T>> implements MinMax<T> {
T[] vals;
MyClass(T[] o) { vals = o; }
// Return the minimum value in vals.
public T min() {
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0) v = vals[i];
return v;
}
// Return the maximum value in vals.
public T max() {
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) > 0) v = vals[i];
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home