Chapter 14: Generics 347
The output from the program is shown here:
iOb2 is instance of Gen2
iOb2 is instance of Gen
strOb2 is instance of Gen2
strOb2 is instance of Gen
iOb is instance of Gen
In this program,Gen2is a subclass ofGen, which is generic on type parameterT. In
main( ), three objects are created. The first isiOb, which is an object of typeGen
The second isiOb2, which is an instance ofGen2
typeGen2
Then, the program performs theseinstanceoftests on the type ofiOb2:
// See if iOb2 is some form of Gen2.
if(iOb2 instanceof Gen2<?>)
System.out.println("iOb2 is instance of Gen2");
// See if iOb2 is some form of Gen.
if(iOb2 instanceof Gen<?>)
System.out.println("iOb2 is instance of Gen");
As the output shows, both succeed. In the first test,iOb2is checked againstGen2<?>. This
test succeeds because it simply confirms thatiOb2is an object of some type ofGen2object.
The use of the wildcard enablesinstanceofto determine ifiOb2is an object of any type of
Gen2. Next,iOb2is tested againstGen<?>, the superclass type. This is also true because
iOb2is some form ofGen, the superclass. The next few lines inmain( )show the same
sequence (and same results) forstrOb2.
Next,iOb, which is an instance ofGen
// See if iOb is an instance of Gen2, which it is not.
if(iOb instanceof Gen2<?>)
System.out.println("iOb is instance of Gen2");
// See if iOb is an instance of Gen, which it is.
if(iOb instanceof Gen<?>)
System.out.println("iOb is instance of Gen");
The firstiffails becauseiObis not some type ofGen2object. The second test succeeds because
iObis some type ofGenobject.
Now, look closely at these commented-out lines:
// The following can't be compiled because
// generic type info does not exist at run time.
// if(iOb2 instanceof Gen2
// System.out.println("iOb2 is instance of Gen2
As the comments indicate, these lines can’t be compiled because they attempt to compare
iOb2with a specific type ofGen2, in this case,Gen2