Type Inference with Generics

When type inference is used, the declaration syntax for a generic reference and instance creation has this general form:

class-name <type-arg-list> var-name = new class-name <> (cons-arg-list);

Ex:

MyClass<Integer,String> mcOb = new MyClass<Integer,String>(98, "A String");

MyClass<Integer,String> mcOb = new MyClass <>(98, "A String");

Type inference can also be applied to parameter passing. For example, if the following method is added to MyClass,

boolean isSame(MyClass<T,V> o)

{

if(ob1 == o.ob1&& ob2 == o.ob2)

return true;

else

return false;

}

Generic Restrictions

They involve creating objects of a type parameter, static members, exceptions,and arrays.

Type Parameters Can’t Be Instantiated

// Can't create an instance of T.
class Gen<T> {
 T ob;
 Gen() {
 ob = new T(); // Illegal!!!
 }
}

Here, it is illegal to attempt to create an instance of T as the compiler does not know what type of object to create.

Restrictions on Static Members

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;
 }
}

We can’t declare static members that use a type parameter declared by the enclosing class, we can declare static generic methods, which define their own type parameters.

Generic Array Restrictions

  • We cannot instantiate an array whose element type is a type parameter.
  • We cannot create an array of type-specific generic references.
// Generics and arrays.
class Gen<T extends Number> 
{
 T ob;
 T vals[]; // OK
 Gen(T o, T[] nums) {
 ob = o;
 // This statement is illegal.
 // vals = new T[10]; // can't create an array of T
 // But, this statement is OK.
 vals = nums; // OK to assign reference to existent array
 }
}
class GenArrays {
 public static void main(String args[]) {
 Integer n[] = { 1, 2, 3, 4, 5 };
 Gen<Integer> iOb = new Gen<Integer>(50, n);
 // Can't create an array of type-specific generic references.
 // Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong!
 // This is OK.
 Gen<?> gens[] = new Gen<?>[10]; // OK
 }
}

Generic Exception Restriction

A generic classcannot extend Throwable.This means that wecannot create generic exception classes.

results matching ""

    No results matching ""