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 ?
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 ofStack. In a static context (the main method), there is no instance ofStackto refer to. Thus the compiler indicates it can not construct aNode.If you make
Nodea static class (or regular outer class), then it will not need a reference toStackand 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.