无法从静态上下文引用非静态变量

时间:2013-11-19 04:18:29

标签: java static non-static

我正在尝试从main方法中的createFile类调用我的OpenFile方法,但我不断收到错误,说我无法从静态上下文中调用非静态变量。

我确实尝试在我的main方法中调用OpenFile of = new OpenFile();,但是这没有用,所以我目前在我的main方法上面声明OpenFile哪个工作正常,但每次我尝试使用一个在OpenFile方法中我得到了同样的错误。

我已尝试使用static添加一些内容,但这只会导致我的IDE显示错误的sym类型错误,我认为这是由导致其他错误的任何内容引起的。

以下是来自createFile的{​​{1}}:

OpenFile

这是我的主要方法:

public class OpenFile {

    private Formatter file;

    public void createFile() throws FileNotFoundException{

        try{
            file = new Formatter("test.txt");
        } catch(Exception e) {
            System.out.println("Error creating file.");
    }
    }

与Formatter有关吗?我以前从未使用过它。

感谢。

4 个答案:

答案 0 :(得分:5)

OpenFile of = new OpenFile();

应该是

static OpenFile of = new OpenFile();

您正在使用static void main方法访问它。如果未将此变量声明为static,则在静态执行该方法时,该变量将无法使用。

答案 1 :(得分:2)

因为java中的主要方法是所有初学者中最受欢迎的方法 他们试图在程序代码中遇到 "non-static variable cannot be referenced from a static context" 编译器错误,当他们尝试访问Java中main的非静态成员变量时

请看一下这篇文章 的 Why non-static variable cannot be referenced from a static context?


在您的情况下,您必须使OpenFile of = new OpenFile();实例化为静态,如下所示,以便在main方法中访问静态方法。

static OpenFile of = new OpenFile();  // should be static for accessing within main method
public static void main(String[] args) {

    of.createFile();
    intro();
    createAndShowRibbon();
    createAndShowNormalUI();

}

答案 2 :(得分:1)

以下是非静态的。

OpenFile of = new OpenFile();

但你是从主方法调用它,这是静态的。

尝试更改为:

static OpenFile of = new OpenFile();

答案 3 :(得分:1)

在静态方法中,你可以调用静态的Class方法或变量 但是你不能在

中调用实例变量或方法