This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Problem: Non-static variables cannot be referenced in a static context

I wrote the test code like this:

class MyProgram
{
    int count = 0;
    public static void main(String[] args)
    { System.out.println(count); }}Copy the code

But the following error occurs

Main.java:6: error: non-static variable count cannot be referenced from a static context
        System.out.println(count);
Copy the code

How do I make my methods recognize class variables?

answer

You must understand the difference between a class and an instance of that class. If you see a car on the street, you can immediately know it’s a car, even if you can’t make out the make or type. That’s because you’re comparing what you’re seeing to the class “car.” This class contains everything that looks like a car. Think of it as a template or an idea.

Also, the car you see is an instance of the class “car” because it has all the attributes you would expect to see: someone is driving it, it has an engine and wheels.

So the class is “all cars have a color”, and the instance is “This particular car is red”

In the object-oriented world, you define the class, and inside the class, you define an attribute of type Color. When the class is instantiated (when you create a concrete instance), memory is allocated to the color property, and you can give the concrete instance a color. Because these properties are concrete, they are non-static.

Static properties and methods are shared with all instances. They are used for values of concrete classes rather than concrete instances. For methods, this is usually a global helper method (such as integer.parseint ()). For fields, it is usually constant (like the car type, which comes from a finite set that doesn’t change very often).

To solve your problem, you need to instantiate an instance of your class (creating an object) so that the runtime can allocate memory for that instance (otherwise, different instances will overwrite each other, which you don’t want).

In your code, try using the following code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch(Exception e) { e.printStackTrace (); }}// Instance variables

public void run (String[] args) throws Exception
{
   // Your code
}
Copy the code

The new main() method creates an instance of the class it contains (which may sound strange, since main() was created with a class rather than an instance, so it can) and then calls an instance method (run()).

The article translated from Stack Overflow:stackoverflow.com/questions/2…