Java Reference
In-Depth Information
In this section we will explore how to write a class called
LinkedIntList
that will
be a parallel of the
ArrayIntList
class of Chapter 15.
So far we have been discussing the low-level details of how to manipulate the nodes
of a class. In general, we want to provide a potential client with a simple interface
that doesn't require the client to understand these low-level details. For example, the
ArrayIntList
class that we examined in Chapter 15 uses an array as its underlying
structure, but a client of the class never has to know that. In a similar way, we'd like
to define a
LinkedIntList
class that a client can access without having to under-
stand that it is implemented by means of a linked list of nodes.
First we have to consider the set of fields that we need. As we've seen, we can get
to any element in the list as long as we have a reference to the front of the list. So at a
minimum we need a reference to the front of the list:
public class LinkedIntList {
private ListNode front;
...
}
There are several other fields we could add to improve efficiency. Two of the most
commonly added fields keep track of the length of the list and keep a reference to the
back of the list. But for this first version, we will keep it simple and store just a refer-
ence to the front of the list.
Notice that for this class, the field
front
is declared to be private. We do that to
guarantee that the class is well encapsulated. But what about those public fields in the
node class? In general public fields are a bad idea. But they're not of great concern in
this case because we're going to make sure that only our
LinkedIntList
object will
ever manipulate individual nodes. By the time we complete this program, we will
have two classes: one for individual nodes of a list and one for the list itself. We'll be
careful to have a clean, well-encapsulated list object, but we don't have to worry
about doing the same thing for the node class.
Some people prefer to encapsulate even node objects to keep things simple, but if
you want to learn how complex classes are written, it is important to understand this
convention. When we are writing code to interact with a client, we want everything to
be completely encapsulated. But when we are writing code that is seen only by the
implementation, we can be more relaxed. As an analogy, think of how you behave in
public versus in your own home. In your own home you might walk around in a
bathrobe and slippers because you know that only you and your family have access to
your home. You wouldn't tend to wear a bathrobe and slippers out in public. As
another example, think of the post office boxes you find at a post office. Those post
office boxes are locked for security, just like an encapsulated object, because anyone
Search WWH ::
Custom Search