Run-Time Type Comparisons Within a Generic Hierarchy

The instanceof operator can be applied to objects of generic classes.

 
class Gen<T> {
  T ob;

  Gen(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

public class Main {
  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");
    System.out.println("iOb2 is instance of Gen2"+(iOb2 instanceof Gen2<?>));
    System.out.println("iOb2 is instance of Gen"+(iOb2 instanceof Gen<?>));
    System.out.println("strOb2 is instance of Gen2"+(strOb2 instanceof Gen2<?>));
    System.out.println("strOb2 is instance of Gen"+(strOb2 instanceof Gen<?>));
    System.out.println("iOb is instance of Gen2"+(iOb instanceof Gen2<?>));
    System.out.println("iOb is instance of Gen"+(iOb instanceof Gen<?>));
  }
}
  

Casting

You can cast one instance of a generic class into another only if the two are compatible and their type arguments are the same.

For example, assuming the foregoing program, this cast is legal:

 
class Gen<T> {
  T ob;

  Gen(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

public class Main {
  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");
    iOb = (Gen<Integer>) iOb2;
  }
}
  

because iOb2 is an instance of Gen<Integer>. But, this cast:

 
class Gen<T> {
  T ob;

  Gen(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

public class Main {
  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");
    //iOb = (Gen<Long>) iOb2;//wrong
  }
}
  

is not legal because iOb2 is not an instance of Gen<Long>.

Home 
  Java Book 
    Language Basics  

Generics:
  1. Generic Class
  2. Generic Bounded Types
  3. Generic Wildcard Arguments
  4. Generic Bounded Wildcards
  5. Generic Method
  6. Generic Constructors
  7. Generic Interfaces
  8. Raw Types and Legacy Code
  9. Generic Class Hierarchies
  10. Run-Time Type Comparisons Within a Generic Hierarchy
  11. Overriding Methods in a Generic Class
  12. Generic Restrictions
  13. Generic Array Restrictions