non-static class cannot be referenced from a static context

Bin picture Bin · Nov 14, 2012 · Viewed 25k times · Source

Possible Duplicate:
Why do I get “non-static variable this cannot be referenced from a static context”?

Here are the codes

public class Stack
{
    private class Node{
        ...
    }
    ...
    public static void main(String[] args){
         Node node = new Node(); // generates a compiling error
    }
}  

the error says:

non-static class Node cannot be referenced from a static context

Why shouldn't I refer the Node class in my main() method ?

Answer

Emil Sit picture Emil Sit · Nov 14, 2012

A non-static nested class in Java contains an implicit reference to an instance of the parent class. Thus to instantiate a Node, you would need to also have an instance of Stack. In a static context (the main method), there is no instance of Stack to refer to. Thus the compiler indicates it can not construct a Node.

If you make Node a static class (or regular outer class), then it will not need a reference to Stack and can be instantiated directly in the static main method.

See the Java Language Specification, Chapter 8 for details, such as Example 8.1.3-2.