Non-static variable cannot be referenced from a static context

840    Asked by Kaalappanshingh in Data Science , Asked on Jul 12, 2021

Here is the code

class method
{
    int counter = 0;
    public static void main(String[] args)
    {
        System.out.println(counter);
    }
}
It gave me this error.

Main.java:6: error: non-static variable counter cannot be referenced from a static context

        System.out.println(counter);

                           ^

How do I make it recognize the variables of the class?


Answered by tom MITCHELL

Getting error ”cannot be referenced from a static context java” because a reference cannot be made from a static to a non-static method. To make it clear, go through the differences below.


Static variables are class variables that belong to the class with only one instance created initially. Whereas, non-static variables are initialized every time you create an object for the class.

You have not created an object hence non-static does not exist and static always do that is why an error is shown

Try the given statements instead:

    Object instance = new Constuctor().methodCall();

or

    primitive name = new Constuctor().methodCall();


Your Answer

Interviews

Parent Categories