Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a static inner class [duplicate]

Tags:

java

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);
    }

}
like image 268
topsail Avatar asked Oct 19 '22 20:10

topsail


1 Answers

No, Static inner classes are classes which dont require an instance of the enclosing type, it is not the same thing as Static when used in the context of a method or field. Static for an inner class essentailly makes them a top level class. When you declare a non static inner class it has implicit access to the instance fields and methods of the enclosing type, thus making an instance of said type a requirement. Static classes dont have that luxury, and therefore dont require an instance of the enclosing type.

like image 75
Mark W Avatar answered Oct 22 '22 09:10

Mark W