Run-Time Type Comparisons Within a Generic Hierarchy : Generic Class Hierarchies « Generics « Java Tutorial






The run-time type information operator instanceof: determines if an object is an instance of a class. The instanceof operator can be applied to objects of generic classes.

class Gen<T> {  
  T ob; 
    
  Gen(T o) {  
    ob = o;  
  }  
  
  T getObject() {  
    return ob;  
  }  
}  
 
class Gen2<T> extends Gen<T> { 
  Gen2(T o) { 
    super(o); 
  } 
} 
 
public class MainClass {  
  public static void main(String args[]) {  
    Gen<Integer> iOb = new Gen<Integer>(88); 
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);  
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");  
 
    if(iOb2 instanceof Gen2<?>){  
      System.out.println("iOb2 is instance of Gen2"); 
    }
    if(iOb2 instanceof Gen<?>){  
      System.out.println("iOb2 is instance of Gen"); 
    }
    if(strOb2 instanceof Gen2<?>){  
      System.out.println("strOb is instance of Gen2"); 
    }
    if(strOb2 instanceof Gen<?>){  
      System.out.println("strOb is instance of Gen"); 
    }
    if(iOb instanceof Gen2<?>){  
      System.out.println("iOb is instance of Gen2"); 
    }
    if(iOb instanceof Gen<?>){  
      System.out.println("iOb is instance of Gen"); 
    }
    // The following can't be compiled because 
    // generic type info does not exist at runtime.
//    if(iOb2 instanceof Gen2<Integer>)  
//      System.out.println("iOb2 is instance of Gen2<Integer>"); 
  }  
}
iOb2 is instance of Gen2
iOb2 is instance of Gen
strOb is instance of Gen2
strOb is instance of Gen
iOb is instance of Gen








12.7.Generic Class Hierarchies
12.7.1.Generic Class Hierarchies: uses a generic superclass
12.7.2.A subclass can add its own type parameters, if needed.
12.7.3.A Generic Subclass: a nongeneric class can be the superclass of a generic subclass
12.7.4.Run-Time Type Comparisons Within a Generic Hierarchy
12.7.5.Casting within a generic class hierarchy
12.7.6.Overriding Methods in a Generic Class