Java Reference
In-Depth Information
But this won't compile because ExtendedValue is attempting to implement
both Comparable<Value> and Comparable<ExtendedValue> and that is not per-
mitted. Once you extend or implement a parameterized type you fix that
parameterization for the current class and all subclasses. So you need
to think carefully about the implications of that. In the case of Compar-
able you have little choice but to accept the restriction, and although
you can't change the type parameterization, you can override the im-
plementation of compareTo to ensure that a subclass instance is accep-
ted for comparison while a superclass instance is rejected. Recall from
the SortedCollection example on page 258 that if you want to accept a
Comparable object, the correct approach is to declare Comparable<?super T>
rather than Comparable<T> . This is not only more general (as previously
explained), it also allows for the fact that a comparable class T may not
actually be able to implement Comparable<T> .
Generic types are a powerful tool for writing your programs more ef-
fectively, but they are a tool that is difficult to master and can easily be
misused. A full treatment of generic types requires an understanding of
type theoryin particular the characteristics of covariant and contravari-
ant typingthat is beyond the scope of this topic. If you are interested
there is additional material on the subject listed in " Further Reading " on
page 755 .
Nearly all men can stand adversity, but if you want to test a man's
character, give him power.
Abraham Lincoln
 
Search WWH ::




Custom Search