Some notes on inner classes - part 1
A Linked List with a private inner class - the usual case
public class LinkedList
{
private class Node
{
private String name;
private Node next;
public Node(String s)
{
name=new String(s);
next=null;
}
public Node getNext()
{ return next;}
public void setNext(Node n)
{
next=n;
}
public String toString()
{
return name;
}
} // end of inner class Node definition
private Node front;
public LinkedList()
{
front=null;
}
public void insertFront(String s)
{
Node newNode=new Node(s);
newNode.setNext(front);
front=newNode;
}
public void printTheList()
{
printForward(front);
}
private void printForward(Node x)
{
if (x!=null)
{
System.out.println(x);
printForward(x.getNext());
}
}
}// end of class LinkedList definition
------------------------------------------------------------
Using the linked list:
public class UseLinkedList
{
public static void main(String [] args)
{
LinkedList myList=new LinkedList();
myList.insertFront("bill");
myList.insertFront("sue");
myList.insertFront("mary");
myList.printTheList();
}
}