Java Generic Restrictions

In this chapter you will learn:

  1. Type Parameters Can't Be Instantiated
  2. What are restrictions on static members
  3. What are restrictions on generic array

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;//from   w  w w. j  a  v a2 s. c o  m

  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;
//  ww  w .  ja  va2  s. com
  // 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;//w ww  .  j  av  a 2  s  .  com
  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
  }
}

Next chapter...

What you will learn in the next chapter:

  1. A growable int array
Home »
  Java Tutorial »
    Java Langauge »
      Java Generics
Java Generic Type
Java Generic Bounded Types
Java Generic Method
Java Generic Constructors
Java Generic Parameter Wildcard
Java Generic interface
Java Raw Types and Legacy Code
Java Generic Class Hierarchies
Java generic types cast
Java Generic Restrictions