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.