Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-static class cannot be referenced from a static context [duplicate]

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 ?

like image 927
Bin Avatar asked Nov 14 '12 05:11

Bin


People also ask

How do you fix error non-static variable this Cannot be referenced from a static context?

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.

Why non-static method Cannot be referenced for a static context?

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 you access a non-static variable in the static context?

“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.

Why static method Cannot use non-static data member?

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.)


1 Answers

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.

like image 74
Emil Sit Avatar answered Sep 19 '22 07:09

Emil Sit