Generic Restrictions

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;

  // 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.

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