Java Reference
In-Depth Information
private
class
Node
{
private
T data;
private
Node next;
. . .
}
// end Node
}
// end LList
17.7
So far, nothing should be new to you. Now imagine that we want
LList
to serve as a base class for
another class that you are developing. You saw in the previous section of this chapter that a sub-
class of
LList
—just like a client of
LList
—cannot access by name anything declared as private
within
LList
. That is, a subclass cannot access the data field
firstNode
, the method
getNodeAt
, or
the class
Node
, as Figure 17-1 illustrates. If we want to extend the capability of
LList
and do so
efficiently, the subclass will need access to these aspects of the class—in other words, to the under-
lying data structure.
FIGURE 17-1
A derived class of the class
LList
cannot access or change
anything that is private within
LList
LList
Private data fields:
firstNode
numberOfEntries
Private method:
getNodeAt
Private inner class:
Node
Any subclass (derived class)
• Cannot access or change
firstNode
• Cannot change
numberOfEntries
• Cannot invoke
getNodeAt
• Cannot create an instance of
Node
• Cannot access or change fields of an existing node
We can revise
LList
to make it more suitable as a base class by providing its subclasses con-
trolled access to items that are hidden from a client. First, let's recall protected access, which we
discussed in Segment C.13 of Appendix C:
Note:
Protected access
You can access a protected method or data field by name only within its own class definition
C
,
within any subclass of
C
, or within any class in the same package as
C
.