Java Reference
In-Depth Information
Node Inner Classes
You can make a linked list, or any similar data structures, self-contained by making the
node class an inner class. In particular, you can make the class LinkedList1 more self-
contained by making Node1 an inner class, as follows:
public class LinkedList1
{
private class Node1
{
< The rest of the definition of Node1 can be
the same as in Display 15.2. >
}
private Node1 head;
< The constructor and methods in Display 15.3 are inserted here. >
}
Note that we've made the class Node1 a private inner class. If an inner class is not
intended to be used elsewhere, it should be made private. Making Node1 a private
inner class hides all objects of the inner class and avoids a privacy leak.
If you are going to make the class Node1 a private inner class in the definition of
LinkedList1 , then you can safely simplify the definition of Node1 by eliminating the
accessor and mutator methods (the set and get methods) and just allowing direct
access to the instance variables ( item , count , and link ) from methods of the outer
class. In Display 15.7, we have written a class similar to LinkedList1 in this way. The
rewritten version, named LinkedList2 , is like the class LinkedList1 in Display 15.3 in
that it has the same methods that perform basically the same actions. To keep the dis-
cussion simple, LinkedList2 has only one data field instead of two. We could easily
have retained the two data fields, but we wanted a notationally simple example with-
out any distracting details. (See Self-Test Exercise 8 for a version that has the same
kind of data in each node as in the nodes of LinkedList1 .)
Display 15.7 A Linked List Class with a Node Inner Class (part 1 of 3)
1 public class LinkedList2
2{
3
private class Node
4
{
5
private String item;
6
private Node link;
7
public Node( )
8
{
9
item = null ;
10
link = null ;
11
}
Search WWH ::




Custom Search