Java Reference
In-Depth Information
3.11. Designing a Class to Be Extended
The Attr class is an example of a well-designed classit follows the design
principles that you learned in Chapter 2 . The fields of the class are
private and accessible only through accessor methods, thereby protect-
ing them from modifications that violate the class's contract. The Attr
class presents a clean interface to users of the class and at the same
time decouples itself from those classes to allow its own implementation
to change in the future.
Given that ColorAttr extends Attr , should we have designed Attr differ-
ently to make it more suitable for extension? Should the name and value
fields have been protected , instead of private , so that a subclass could
access them directly? Such decisions require careful thought and con-
sideration of both the benefits and consequences. Making the Attr fields
protected would not benefit a subclass because all of the actions that can
be performed on those fields can be done via the public methods that
Attr provides. On the other hand, making the fields protected would pre-
vent any future modifications to the implementation of Attr because sub-
classes could depend on the existence and type of those fields, as well as
direct access to them. So in this case, Attr 's current design is suited for
extension as well as for general use.
In our linked-list queue class, SingleLinkQueue , we did make the head and
tail fields protected . In that case there was a great performance be-
nefit in allowing the subclass to directly access cells of the linked listit
would be impractical to implement the override of add in PriorityQueue
if the only tools available to use were the original add and remove meth-
ods. The low-level nature of the SingleLinkQueue class also means that we
are not concerned about locking in implementation detailsit is after all a
linked-list implementation of a queue and that doesn't really leave much
scope for change. If we had written a more general queue class that just
happened to be using a linked-list implementation, then it would be a dif-
ferent story.
A non-final class has two interfaces. The public interface is for program-
mers using your class. The protected interface is for programmers ex-
 
Search WWH ::




Custom Search