non-static class cannot be referenced from a static context [duplicate]
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.
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax : OuterClass.InnerClass innerObject = outerObject.new InnerClass();
public static void main(String[] args){
Stack stack = new Stack();
Stack.Node node = new Stack().new Node();
}
or
public class Stack
{
private class Node{
...
}
...
...
...
public static void main(String[] args){
Node node = new Stack().new Node();
}
}