Java Reference
In-Depth Information
Can you create a Wrapper<T> object of an unknown type? Let's assume that John cooks something for you. He
packs the food in a packet and hands it over to you. You hand over the packet to Donna. Donna asks you what is inside
the packet. Your answer is that you do not know. Can John answer the same way you did? No. He must know what
he cooked because he was the person who cooked the food. Even if you did not know what was inside the packet,
you had no problem in carrying it and giving it to Donna. What would be your answer if Donna asked you to give her
vegetable from the packet? You would say that you do not know if a vegetable is inside the packet.
Here are the rules for using a wildcard (unknown) generic type. Since it does not know its type, you cannot use it
to create an object of its unknown type. The following code is illegal:
// Cannot use <?> with new operator. It is a compile-time error.
new Wrapper<?>("");
It generates the following error:
error: unexpected type
new Wrapper<?>("");
^
required: class or interface without bounds
found: ?
1 error
As you were holding the packet of unknown food type (John knew the type of food when he cooked the food), a
wildcard generic type can refer to a known generic type object, as shown:
Wrapper<?> unknownWrapper = new Wrapper<String>("Hello");
There is a complicated list of rules as to what a wildcard generic type reference can do with the object. However,
there is a simple rule of thumb to remember. The purpose of using generics is to have compile-time type-safety in Java
programs. As long as the compiler is satisfied that the operation will not produce any surprising results at runtime, it
will allow the operation on the wildcard generic type reference.
Let's apply the rule of thumb to your unknownWrapper reference variable. One thing that this unknownWrapper
variable is sure about is that it refers to an object of the Wrapper<T> class of a known type. However, it does not know
what that known type is. Can you use the following get() method?
String str = unknownWrapper.get(); // A compile-time error
The above statement will not compile. The compiler generates the following error:
error: incompatible types: CAP#1 cannot be converted to String
String str = unknownWrapper.get(); // A compile -time error
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 error
The compiler knows that the get() method of the Wrapper<T> class returns an object of type T . However, for
the unknownWrapper variable, type T is unknown. Therefore, the compiler cannot make sure that the method call,
unknownWrapper.get() , will return a String and its assignment to str variable is fine at runtime. All you have to do is
convince the compiler that the assignment will not throw a ClassCastException at runtime. Will the following line of
code compile?
Object obj = unknownWrapper.get(); // OK
 
Search WWH ::




Custom Search