Java Generic Hierarchy Run-Time Type Comparisons

Introduction

The following code shows the type compatibility implications of a generic hierarchy:


// Use the instanceof operator with a generic class hierarchy.  
class MyClass<T> {
  T ob;//w  w w.ja v  a2  s.  c om

  MyClass(T o) {
    ob = o;
  }

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

class MySubclass<T> extends MyClass<T> {
  MySubclass(T o) {
    super(o);
  }
}

// Demonstrate run-time type ID implications of generic
// class hierarchy.
public class Main {
  public static void main(String args[]) {

    MyClass<Integer> iOb = new MyClass<Integer>(88);

    MySubclass<Integer> iOb2 = new MySubclass<Integer>(99);

    MySubclass<String> strOb2 = new MySubclass<String>("Generics Test");

    if (iOb2 instanceof MySubclass<?>) {
      System.out.println("iOb2 is instance of Gen2");
    }
    if (iOb2 instanceof MyClass<?>) {
      System.out.println("iOb2 is instance of Gen");
    }

    if (strOb2 instanceof MySubclass<?>) {
      System.out.println("strOb is instance of Gen2");
    }
    if (strOb2 instanceof MyClass<?>) {
      System.out.println("strOb is instance of Gen");
    }
    if (iOb instanceof MySubclass<?>) {
      System.out.println("iOb is instance of Gen2");
    }
    if (iOb instanceof MyClass<?>) {
      System.out.println("iOb is instance of Gen");
    }
  }
}



PreviousNext

Related