Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 14: Generics 345


// Return ob.
T getob() {
return ob;
}
}


// Create a Gen object.
class HierDemo2 {
public static void main(String args[]) {


// Create a Gen object for String.
Gen<String> w = new Gen<String>("Hello", 47);

System.out.print(w.getob() + " ");
System.out.println(w.getnum());
}
}


The output from the program is shown here:


Hello 47

In the program, notice howGeninheritsNonGenin the following declaration:

class Gen extends NonGen {


BecauseNonGenis not generic, no type argument is specified. Thus, even thoughGen
declares the type parameterT, it is not needed by (nor can it be used by)NonGen. Thus,
NonGenis inherited byGenin the normal way. No special conditions apply.


Run-Time Type Comparisons Within a Generic Hierarchy


Recall the run-time type information operatorinstanceofthat was described in Chapter 13.
As explained,instanceofdetermines if an object is an instance of a class. It returns true if
an object is of the specified type or can be cast to the specified type. Theinstanceofoperator
can be applied to objects of generic classes. The following class demonstrates some of the
type compatibility implications of ageneric hierarchy:


// Use the instanceof operator with a generic class hierarchy.
class Gen {
T ob;


Gen(T o) {
ob = o;
}

// Return ob.
T getob() {
return ob;
}
}

Free download pdf