Java Reference
In-Depth Information
// We could store an Object in stringWrapper using objectWrapper
objectWrapper.set(new Object());
// The following statement will throw a runtime ClassCastException
String s = sgw.get();
Do you see the danger of allowing an assignment like objectWrapper = stringWrapper ? The compiler cannot
make sure that stringWrapper will store only a reference of String type if this assignment was allowed.
Remember that a String is an Object because String is a subclass of Object . However, Wrapper<String> is not
a Wrapper<Object> . The normal supertype/subtype rules do not apply with parameterized types. Don't worry about
memorizing this rule if you do not understand it. If you attempt to make an assignment like the one shown above, the
compiler will tell you that you can't.
Raw Type
Implementation of generic types in Java is backward compatible. If an existing non-generic class is rewritten to take
advantage of generics, the existing code that uses the non-generic version of the class should keep working. The
code may use (though it is not recommended) a non-generic version of a generic class by just omitting references
to the generic type parameters. The non-generic version of a generic type is called a raw type. Using raw types is
discouraged. If you use raw types in your code, the compiler will generate unchecked warnings, as shown in the
following snippet of code:
Wrapper rawType = new Wrapper("Hello"); // An unchecked warning
Wrapper<String> genericType = new Wrapper<String>("Hello");
genericType = rawType; // An unchecked warning
rawType = genericType;
The compiler generates the following warnings when the above snippet of code is compiled:
warning: [unchecked] unchecked call to Wrapper(T) as a member of the raw type Wrapper
Wrapper rawType = new Wrapper("Hello"); // An unchecked warning
^
where T is a type-variable:
T extends Object declared in class Wrapper
warning: [unchecked] unchecked conversion
genericType = rawType; // An unchecked warning
^
required: Wrapper<String>
found: Wrapper
2 warnings
 
Search WWH ::




Custom Search