Java Reference
In-Depth Information
// References to fields originally of type T will be cast to type String
// as will values returned by method calls originally of type T.
}
Normally you don't need to be aware of this, but suppose you derive a new class from type
LinkedList<String> :
public class SpecialList extends LinkedList<String> {
// Override base class version of addItem() method
@Override
public void addItem(String item) {
// New code for the method...
}
// Rest of the code for SpecialList...
}
Here you are trying to override the version of addItem() that your class inherits from
LinkedList<String> . Because the compiler chooses to compile the method to bytecodes with a different
signature, as your method is written it doesn't override the base class method at all. The base class method
parameter is of type Object , whereas the parameter for your version of the method is of type String . To fix
the problem the compiler creates a bridge method in your derived SpecialList class that looks like this:
public void addItem(Object item) {
addItem((String)item); // Call derived class version
}
The effect of the bridge method is to convert any calls to the inherited version of addItem() to a call to
your version, thus making your attempt at overriding the base class method effective.
However, the approach adopted by the compiler has implications for you. You must take care not to
define methods in your derived class that have the same signature as an inherited method. Because the com-
piler changes the parameter types and return types involving type variables to their bounds, you must con-
sider the inherited methods in these terms when you are defining your derived class methods. If a method
in a class that you have derived from a generic type has the same signature as the erasure of an inherited
method, your code does not compile.
SUMMARY
In this chapter you learned the essentials of how generic types are defined and used. Generic types add a
powerful capability to your Java programming armory. In the next chapter you see how the java.util pack-
age provides you with an extensive range of standard generic types that you can use in your programs for
managing collections of data items.
Search WWH ::




Custom Search