I have a question about use of static inner class in the following code, adapted from Eckel's Thinking in Java 4th edition (page 625).
The code uses a static inner class called Node. When you create a Stack structure, you can then push the nodes onto the stack and pop them off - so far so good. But I'm confused about why the node class is static? Wouldn't that mean that there would be only one Node created in the LinkedStack class? How / why is it that in fact you can push many different nodes onto the stack, and then pop them off (which of course is what the stack is supposed to do). In fact, you can change private static class Node
to 'private class Node` and it also works ... so why did Eckels choose static class Node?
In this example, the input is the three words "Phasers", "on", "stun!" and output is "stun!", "on", "Phasers".
public class LinkedStack<T> {
//generic inner class node
private static class Node<U> {
U item;
Node<U> next;
Node() {
item = null;
next = null;
}
Node(U item, Node<U> next) {
this.item = item;
this.next = next;
}
boolean isDummyNode() {
return item == null && next == null;
}
}
//initialize top of stack as a dummy first node
private Node<T> top = new Node<T>();
public void push(T item) {
top = new Node<T>(item, top);
}
public T pop() {
T result = top.item;
if(!top.isDummyNode())
top = top.next;
return result;
}
public static void main(String[] args) {
LinkedStack<String> stack = new LinkedStack<String>();
for(String s : "Phasers on stun!".split(" "))
stack.push(s);
String s;
while((s = stack.pop()) != null)
System.out.println(s);
}
}