The type parameter T is specified by Gen2 and is also passed to Gen in the extends clause.
This means that whatever type is passed to Gen2 will also be passed to Gen. For example,
this declaration,
Gen2<Integer> num = new Gen2<Integer>(100);
passes Integer as the type parameter to Gen. Thus, the ob inside the Gen portion of Gen2
will be of type Integer.
Notice also that Gen2 does not use the type parameter T except to pass it to the Gen
superclass. Thus, even if a subclass of a generic superclass would otherwise not need to
be generic, it still must specify the type parameter(s) required by its generic superclass.
Of course, a subclass is free to add its own type parameters, if needed. For example, here
is a variation on the preceding hierarchy in which Gen2 adds a type parameter of its own:
// A subclass can add its own type parameters.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
}
// A subclass of Gen that defines a second
// type parameter, called V.
class Gen2<T, V> extends Gen<T> {
V ob2;
Gen2(T o, V o2) {
super(o);
ob2 = o2;
}
V getob2() {
return ob2;
}
}
// Create an object of type Gen2.
class HierDemo {
public static void main(String args[]) {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home