THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Or you may be providing a specialized implementation that has been hand-crafted to deal with a particular
kind of element, say String, and so it won't be generic itself and will implement the parameterized interface
List:


class StringList implements List { / ... / }


An existing non-generic class, such as AbstractEventService, may provide base functionality that you
have to extend to use a framework within your application. You might define a concrete implementation that
has no need of generics:


class RemoteEventService extends AbstractEventService {
/ ... /
}


Or you might define a generic service for different kinds of events:


class LocalEventService extends
AbstractEventService { / ... / }


The possibilities really depend on the semantics of the types involved.


When choosing to extend a parameterized type, you need to carefully consider the implications, particularly if
you are implementing an interface, because a class cannot inherit two interface types that are different
parameterizations of the same interface. For example, consider the Comparable interface. If you define a
comparable class Value then it is natural to declare it as:


class Value implements Comparable {
// ...
}


Suppose you now extend Value to add additional state. This ExtendedValue class should define objects
that are comparable only to ExtendedValue objects, so you would expect to be able to define it so:


class ExtendedValue extends Value
implements Comparable { // INVALID!
// ...
}


But this won't compile because ExtendedValue is attempting to implement both Comparable
and Comparable and that is not permitted. 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 Comparable you have little choice but to accept the
restriction, and although you can't change the type parameterization, you can override the implementation of
compareTo to ensure that a subclass instance is accepted for comparison while a superclass instance is
rejected. Recall from the SortedCollection example on page 258 that if you want to accept a

Free download pdf