44

可能重复:
为什么我得到“不能从静态上下文引用的非静态变量”?

这是代码

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

错误说:

不能从静态上下文引用非静态类节点

为什么我不应该在我的 main() 方法中引用 Node 类?

4

6 回答 6

64

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.

于 2012-11-14T06:05:54.000 回答
13

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(); 
    }
}  
于 2012-11-14T06:05:19.117 回答
3

或者您可以在之外声明类Nodepublic class Stack

像这样,

    public class Stack
    {

        public static void main(String[] args){
             Node node = new Node();         
}        
    }  
    class Node{

    }
于 2012-11-14T06:03:55.050 回答
3

Java has two types of nested member classes: static and non-static (aka inner). The Node class is a non-static nested class. In order to create an instance of a Node you must have an instance of a Stack:

Stack s = new Stack();
Node n = s.new Node();
于 2012-11-14T06:09:48.673 回答
2

让你的 ( Node) 类static

private static class Node {
于 2012-11-14T06:02:54.920 回答
1

If you use Eclipse IDE, you would see the explanation when you hover over the error. It should say something like this:

No enclosing instance of type Stack is accessible. Must qualify the allocation with an enclosing instance of type Stack (e.g. x.new A() where x is an instance of Stack).

Here is working code

public static void main(String[] args){
    Stack stack = new Stack();
     Node node = stack.new Node(); 
}
于 2012-11-14T06:09:29.110 回答