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 ?
Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created.
A non-static method is dependent on the object. It is recognized by the program once the object is created. But a static method can be called before the object creation. Hence you cannot make the reference.
“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.
Non-static variables are part of the objects themselves. To use a non-static variable, you need to specify which instance of the class the variable belongs to. But with static methods, there might not even be any instances of the class. (For example, the static methods in Math run without instantiating a Math object.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With