Restrictions in Generics

There are a few restrictions that you need to keep in mind when using generics. They involve
  • creating objects of a type parameter,
  • static members,
  • exceptions,
  • and arrays.

Type Parameters Can’t Be Instantiated
It is not possible to create an instance of a type parameter. For example, consider this class:
class Gen<T>
{
     T ob;
     Gen()
     {
ob = new T();    // Error
     }
}
Here, it is illegal to attempt to create an instance of T. The compiler does not know what type of object to create. T is simply a placeholder.
 

Restrictions on Static Members
No static member can use a type parameter declared by the enclosing class. For example, both of the static members of this class are illegal:
class Gen<T>
{
     static T obj;      // Error – no static variables of type T
     static T fnGet()      // Error – no static method can use T
     {
          return obj;
     }
}

Generic Array Restrictions
There are two important generics restrictions that apply to arrays.
  • First, you cannot instantiate an array whose element type is a type parameter.
  • Second, you cannot create an array of type-specific generic references.
// Generics and arrays – 1
class Gen<T extends Number>
{
     T Sum;
     T Arr [];
     Gen()
     {
          Arr = new T[5]; // Invalid
     }
}
class GArr
{
public static void main(String as[])
{
     // Error – cannot create an array of type–specific generic references.
     Gen<Integer> obj2[] = new Gen<Integer>[10];
}
}
Arr = new T[5] – is Invalid, since the compiler cannot determine what type of array to create.
// Generics and arrays – 2
class Gen<T extends Number>
{
     T Sum;
     T Arr [];
     Gen(T[] A)
     {
          Arr = A;  // Valid
     }
}
class GArr
{
public static void main(String as[])
{
     Integer N[] = {1,2,3};
     Gen<Integer> obj1 = new Gen<Integer>(N);
}
}
 
 

Generic Exception Restriction
A generic class cannot extend Throwable – so cannot create generic exception classes.