Ambiguity errors can be tricky to fix. For example, if you know that V will always be some
type of String, you might try to fix MyGenClass by rewriting its declaration as shown here:
class MyGenClass<T, V extends String> {
// almost OK!
This change causes MyGenClass to compile, and you can even instantiate objects like the
one shown here:
MyGenClass<Integer, String> x = new MyGenClass<Integer, String>();
This works because Java can accurately determine which method to call. However,
ambiguity returns when you try this line:
MyGenClass<String, String> x = new MyGenClass<String, String>();
In this case, since both T and V are String, which version of set( ) is to be called?
Frankly, in the preceding example, it would be much better to use two separate method
names, rather than trying to overload set( ). Often, the solution to ambiguity involves the
restructuring of the code, because ambiguity often means that you have a conceptual error
in your design.
Some Generic Restrictions
There are a few restrictions that you need to keep in mind when using generics. They
involve creating objects of a type parameter, static members, exceptions, and arrays. Each is
examined here.
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!!!
Here, it is illegal to attempt to create an instance of T. The reason should be easy to
understand: because T does not exist at run time, how would the compiler know what type
of object to create? Remember, erasure removes all type parameters during the compilation
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;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks