Generics - Restrictions

 Generics - Restriction

Some Generic Restrictions

There are a few restrictions that you need to keep in mind when using generics. They involve

1.   creating objects of a type parameter,

2.   static members,

3.   exceptions,

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

1.   First, you cannot instantiate an array whose element type is a type parameter.

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

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu