Java Reference
In-Depth Information
Our goal, then, is to provide a subclass protected—but limited—access to the underlying chain
of nodes. The subclass should be able to traverse or modify the chain efficiently. However, modifi-
cations to the chain must be done in a way that helps to maintain its integrity.
17.8
To enable a subclass to access the data fields by name without giving this access to the client, we
could declare firstNode and numberOfEntries to be protected. It is more typical, however, to keep
them private and to provide protected methods for only the access we desire. The subclass will need
to access the head reference firstNode , so we provide a protected get method to do this. Since
getLength is public, the subclass can get the value of numberOfEntries .
A subclass likely will need to change firstNode and numberOfEntries , so we could provide
protected methods that do so. But while we want an efficient subclass, we also want to keep our
data structure intact. So we will not allow a subclass to change these fields directly. Instead, we can
provide protected methods that modify our chain of nodes in a way that can satisfy both of our
desires. For example, protected methods can add or delete nodes, updating the chain's length in the
process. No mutators will be available to directly change either the field numberOfEntries or a
node's link. Thus, the subclass can alter the chain efficiently, but we are assured that the nodes will
be linked correctly and the chain's length will be accurate.
17.9
As a result of this discussion, we make the following changes to LList :
1.
We define a protected method getFirstNode , enabling the subclass to access the head refer-
ence firstNode :
protected Node getFirstNode()
{
return firstNode;
} // end getFirstNode
2.
We define protected methods to add and remove nodes, changing firstNode and numberOf -
Entries as necessary:
/** Adds a node to the beginning of a chain. */
protected void addFirstNode(Node newNode)
/** Adds a node to a chain after a given node. */3
protected void addAfterNode(Node nodeBefore, Node newNode)
/** Removes a chain's first node. */
protected T removeFirstNode()
/** Removes the node after a given one. */
protected T removeAfterNode(Node nodeBefore)
The implementations of these methods use the techniques presented in Chapter 14. For
example, addFirstNode has the following definition, assuming that newNode is not null and
the inner class Node has set and get methods:
protected void addFirstNode(Node newNode)
{
assert newNode != null : "null argument in addFirstNode";
newNode.setNextNode(firstNode);
firstNode = newNode;
numberOfEntries++;
} // end addFirstNode
To prevent a subclass from overriding these protected methods, you can declare them
as final.
Search WWH ::




Custom Search