Question

Recently I met with this error

"non-static variable cannot be referenced from a static context"

where I had initialized all the variables in my main method, which is a static method. But after making all the variables static It compiled without an error. Please Can anyone explain why it happens this way?

public class Test2 {

String[] mycharset; 
String chkfor;


public static void main(String[] args){
    mycharset = new String[5];
    chkfor = "k";
    mycharset[0] = "a";
    mycharset[1] = "b";
    mycharset[2] = "c";
    mycharset[3] = "d";
    mycharset[4] = "e";
    }
}
Was it helpful?

Solution

To start explaining this I will have to start with a few basic things.

When making an object based on a class, new Test2(), your object will have its own variables that are declared on the top, String[] mycharset;and String chkfor;

When you declare something as static, then it is to be seen as not a member of the object that are created based on your class, but instead as members of the actual class itself.

So if your class would look like this:

public class Test2 {
    String[] array;
    static String text;
}

and you then made 2 instances of the Test2-class, 2 different objects.

Test2 a = new Test2();
Test2 b = new Test2();

Then a and b would have their own array-variable, but they would share the same text-variable.

This is the same when it comes to methods. When you have a static method, it is "owned" by the class, and non-static methods are "owned" by the objects based on the class.

To the issue:

The warning/error you get is all due to the above explanation. The main-method is static and thereby belong to the class. When you run the main-method, then only the static methods and variables has been initiated.

If you want to initiate the variables in Test2 that aren't static, then you will have to make an object out of Test2.

So what you could do, instead of making the variables static is the following:

public class Test2 {

String[] mycharset; 
String chkfor;


public static void main(String[] args){
    Test2 myTest = new Test2();
        myTest.mycharset = new String[5];
        myTest.chkfor = "k";
        myTest.mycharset[0] = "a";
        myTest.mycharset[1] = "b";
        myTest.mycharset[2] = "c";
        myTest.mycharset[3] = "d";
        myTest.mycharset[4] = "e";
    }
}

By doing it this way you are accessing the non-static variables directly on the object that you have created with the Test2-class as a template.

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