0 votes
in JAVA by
Non-static variable cannot be referenced from a static context

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?

1 Answer

0 votes
by
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 which 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();

ans2-

First of all you must know the difference between the class and its instance. All static variables do not belong to any particular instance of the class, they are recognized with the name of that particular class. Static methods do not belong to any particular instance, they can access only static variables. Imagine calling MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how will it know which variable to use? That's why you can only use static variables from static methods and they do NOT belong to any particular instance as mentioned above.

The solution for your code is that you either make your fields static or your methods non-static, try making your main function similar to this

class method

{

  public static

void main(String[] args) {

method myprogram = new method();

myprogram.start();

}

public void start() {

}

  }

Related questions

+2 votes
asked May 31, 2020 in JAVA by SakshiSharma
0 votes
asked Dec 7, 2020 in JAVA by SakshiSharma
...