无法从静态上下文引用非静态类 [英] non-static class cannot be referenced from a static context

查看:126
本文介绍了无法从静态上下文引用非静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么我得到非静态变量,这不能从静态上下文中引用?


以下是代码

 公共类Stack 
{
私有类节点{
...
}
...
public static void main (String [] args){
Node node = new Node(); //生成编译错误
}
}

错误说:


非静态类节点无法从静态上下文引用


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

解决方案

Java中的非静态嵌套类包含对父类的实例的隐式引用。因此,要实例化节点,您还需要一个 Stack 的实例。在静态上下文(main方法)中,没有要引用的 Stack 的实例。因此,编译器指示它不能构造节点



如果你使 Node 一个静态类(或常规外部类),然后它不需要对 Stack 的引用,并且可以直接在静态main方法中实例化。 / p>

请参阅 Java语言规范,第8章了解详细信息,例如例8.1.3-2。


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

这篇关于无法从静态上下文引用非静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆