Source of ClassWithNestedNode.java


  1: //ClassWithNestedNode.java

  3: public class ClassWithNestedNode
  4: {
  5:     Node head;

  7:     public static void main(String[] args)
  8:     {
  9:         ClassWithNestedNode tester = new ClassWithNestedNode();
 10:         tester.createAndModifySequence();
 11:         tester.displaySequenceValues();

 13:     }

 15:     private void createAndModifySequence()
 16:     {
 17:         Node firstNode;
 18:         firstNode = new Node(1);
 19:         firstNode = new Node(3, firstNode);
 20:         firstNode = new Node(5, firstNode);
 21:         firstNode.next = firstNode.next.next;
 22:         head = new Node(7, firstNode);
 23:         head.next.data = 9;
 24:     }

 26:     private void displaySequenceValues()
 27:     {
 28:         Node currentNode = head;
 29:         while (currentNode != null)
 30:         {
 31:             System.out.println(currentNode.data);
 32:             currentNode = currentNode.next;
 33:         }
 34:     }

 36:     //This Node class is now a "nested" class.
 37:     private class Node
 38:     {
 39:         private int data; //Data in the node
 40:         private Node next; //Link to next node

 42:         //Two constructors
 43:         public Node(int data)
 44:         {
 45:             this(data, null);
 46:         }

 48:         public Node
 49:         (
 50:             int data,
 51:             Node next
 52:         )
 53:         {
 54:             this.data = data;
 55:             this.next = next;
 56:         }
 57:     }
 58: }
 59: /*  Note:
 60:     Two class files are produced when you compile this program.
 61:     Exercise: Make the constructors private and re-compile, noting
 62:     that in this case three class files are produced.
 63: */
 64: /*  Output:
 65:     7
 66:     9
 67:     1
 68: */