Generics and Limitations in Java - Erasure and Bounds (Working with Legacy Code)
(Page 3 of 5 )
We mentioned earlier in our discussion of erasure that the resulting type used in place of the type parameter in the raw type for the generic class is the bound of the type variable. Specifically, we have seen many generics with no explicit bounds that defaulted to a bound of type Object. We also showed a quick example of a type that imposed a bound of extends Date and said that the type of its methods would be Date instead of Object. We can now be a little more specific.
The type after erasure used for the parameter type of a generic class is the leftmost bound. That is, the first bound specified after extends becomes the type used in the erasure. This implies that if the type extends a class type, it is always the erased type because it must always come first. But if the type extends only interface types, the choice is up to us. This fine point is important for backward compatibility with nongeneric code. Often when creating generic versions of nongeneric APIs, we have the opportunity to "tighten up" the specification a bit. Being aware of the leftmost bound gives us a way to explicitly control the type of the erased class. For example, suppose we create a generic List class that we only want instantiated on Listable objects, but we'd prefer not to change the API of our old List class, which accepted Object type elements. Our initial attempt:
class List< E extends Listable > { ... }
produces a raw type that accepts only Listable. However, we can insert a somewhat gratuitous additional type, Object, as the leftmost bound in order to get back our old API, without changing the new generic bounds:
class List< E extends Object & Listable > { ... }
Inserting Object doesn't change the actual bounds of the generic class but does change the erased signature.
Next: Wildcards >>
More Java Articles
More By O'Reilly Media
|
This article was excerpted from chapter eight of the book Learning Java, third edition, written by Patrick Niemeyer and Jonathan Knudsen (O'Reilly; ISBN: 0596008732). Check it out today at your favorite bookstore. Buy this book now.
|
|