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;/*java  2 s  .c om*/

  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;
//  ja v  a2 s  .  c  o  m
  // 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;/*  ja va  2  s . co m*/
  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. What is Java Reflection
  2. What are the useful classes we can use to do reflection in Java
Home » Java Tutorial » Generics
Generic Type
Generic Bounded Types
Generic Method
Generic Constructors
Wildcard
Generic interface
Raw Types and Legacy Code
Generic Class Hierarchies
Cast generic types
Generic Restrictions