+12 votes
2 views
in Java by (1.3k points)

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?

3 Answers

+11 votes
by (10.6k points)
edited 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();



 

+13 votes
by (13.2k points)
edited by

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() {

}

  }

0 votes
by (40.3k points)

The very basic and important thing is static variables or static methods are at the class level. And Class level variables or methods get loaded prior to instance-level methods or variables.

Interested in learning Java from basics! Go through this end to end video on Java:

 So, obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it can give you an error as non-static things can not be referred from the static context. 

Note: You just need to take care of Class Level Scope, Instance Level Scope and Local Scope.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...