Question

I'm trying to call my createFile method from the OpenFile class in my main method, but I keep getting the error saying that I cannot call a non-static variable from a static context.

I did try calling OpenFile of = new OpenFile(); inside my main method, but that didn't work so I'm currently declaring OpenFile above my main method which works fine, however every time I try to use one of OpenFiles methods I get the same error.

I've tried prefacing a few things with static but that just causes my IDE to show an Erroneous sym type error, which I think is caused by whatever is causing the other error.

Here is createFile from 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.");
    }
    }

and here is my main method:

OpenFile of = new OpenFile();

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

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

}

Is it something to do with Formatter? I've never used it before.

Thanks.

Was it helpful?

Solution

OpenFile of = new OpenFile();

should be

static OpenFile of = new OpenFile();

You're accessing it from your static void main method. If this variable is not declared static, it will not be available to the method when it is statically executed.

OTHER TIPS

Since main method in java is most popular method among all beginners and they try to put program code there they face "non-static variable cannot be referenced from a static context" compiler error when they try to access a non static member variable inside main in Java which is static.

Please take a look at this article
Why non-static variable cannot be referenced from a static context?


In your case you have to make the OpenFile of = new OpenFile(); instantiation to be static like as shown below in order to access that in main method which is a static method.

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

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

}

The following is non-static.

OpenFile of = new OpenFile();

But you're calling it from a main method, which is static.

Try changing to:

static OpenFile of = new OpenFile();

in the static method u can call Class methods or variables which is static but u can't call instance variables or method in

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top