// 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);
}
}
Although you can't declare static members that use a type parameter declared by the
enclosing class, you can declare static generic methods, which define their own type parameters,
as was done earlier in this chapter.
Generic Array Restrictions
There are two important generics restrictions that apply to arrays. First, you cannot instantiate
an array whose base type is a type parameter. Second, you cannot create an array of type-
specific generic references. The following short program shows both situations:
// 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
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home