Java Tutorial - What are restrictions for Java generic types








Type Parameters Can't Be Instantiated

It is not possible to create an instance of a type parameter. For example, consider this class:

// Can't create an instance of T. 
class Gen<T> {
  T ob;

  Gen() {
    ob = new T(); // Illegal!!!
  }
}




Restrictions on Static Members

No static member can use a type parameter declared by the enclosing class. For example, all of the static members of this class are illegal:

class Wrong<T> {
  // Wrong, no static variables of type T.
  static T ob;
/*  w  w  w  .ja va  2s. c om*/
  // Wrong, no static method can use T.
  static T getob() {
    return ob;
  }

  // Wrong, no static method can access object of type T.
  static void showob() {
    System.out.println(ob);
  }
}

You can declare static generic methods with their own type parameters.





Generic Array Restrictions

You cannot instantiate an array whose base type is a type parameter. You cannot create an array of type specific generic references.

The following short program shows both situations:

class MyClass<T extends Number> {
  T ob;/*from w  w  w  .  j av  a  2s .co  m*/
  T vals[];

  MyClass(T o, T[] nums) {
    ob = o;
    vals = nums;
  }
}

public class Main {
  public static void main(String args[]) {
    Integer n[] = { 1 };
    MyClass<Integer> iOb = new MyClass<Integer>(50, n);
    // Can't create an array of type-specific generic references.
    // Gen<Integer> gens[] = new Gen<Integer>[10]; 
    MyClass<?> gens[] = new MyClass<?>[10]; // OK
  }
}