【问题标题】:Non-static variable of cannot be referenced from a static context [duplicate]不能从静态上下文中引用的非静态变量 [重复]
【发布时间】:2013-12-02 12:12:41
【问题描述】:

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

我确实尝试在我的主要方法中调用OpenFile of = new OpenFile();,但这不起作用,所以我目前在我的主要方法上方声明OpenFile,它工作正常,但是每次我尝试使用OpenFile 之一s 方法我得到同样的错误。

我尝试使用 static 开头一些东西,但这只会导致我的 IDE 显示错误的 sym 类型错误,我认为这是由导致其他错误的任何原因引起的。

这是来自OpenFilecreateFile

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.");
    }
    }

这是我的主要方法:

OpenFile of = new OpenFile();

public static void main(String[] args) {
    // TODO code application logic here

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

}

它与格式化程序有关吗?我以前从来没有用过。

谢谢。

【问题讨论】:

标签: java static non-static


【解决方案1】:
OpenFile of = new OpenFile();

应该是

static OpenFile of = new OpenFile();

您正在通过static void main 方法访问它。如果这个变量没有被声明为static,那么静态执行时,方法将无法使用它。

【讨论】:

  • 似乎运行了!虽然它在我将静态添加到 OpenFile 时运行,但只有当我也将 throws FileNotFoundException 添加到 main 方法时,这是怎么回事?
  • @JoshJahans:您正在调用of.createFile();,这会引发同样的异常。由于它被扔到那里而不是被捕获(使用try { } catch { }),因此必须在下一个方法中抛出或捕获它,在本例中为main
  • 我明白了,谢谢你的帮助!
  • 你不能调用不存在的东西。由于您尚未创建对象,因此非静态方法尚不存在。静态方法(根据定义)始终存在。
【解决方案2】:

由于 ma​​in 方法 在 java 中是所有初学者中最流行的方法,并且 他们尝试将程序代码放在那里,当他们尝试访问非静态成员Java main 中的静态变量时,会遇到编译器错误"non-static variable cannot be referenced from a static context"强>。

请看这篇文章
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();

}

【讨论】:

    【解决方案3】:

    以下是非静态的。

    OpenFile of = new OpenFile();
    

    但你是从一个静态的 main 方法调用它。

    尝试更改为:

    static OpenFile of = new OpenFile();
    

    【讨论】:

      【解决方案4】:

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

      中调用实例变量或方法

      【讨论】:

        猜你喜欢
        • 2011-05-12
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-17
        • 2011-11-30
        相关资源
        最近更新 更多