Generic Restrictions
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;
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;
// 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.
Home
Java Book
Language Basics
Java Book
Language Basics
Generics:
- Generic Class
- Generic Bounded Types
- Generic Wildcard Arguments
- Generic Bounded Wildcards
- Generic Method
- Generic Constructors
- Generic Interfaces
- Raw Types and Legacy Code
- Generic Class Hierarchies
- Run-Time Type Comparisons Within a Generic Hierarchy
- Overriding Methods in a Generic Class
- Generic Restrictions
- Generic Array Restrictions