Non-static variables cannot be referenced in java static methods

Static methods and static variables are objects belonging to a certain class, not belonging to the class.

Because we know that static methods can be used when no instance is created, and a member variable declared as non-static is an object property, which can only be referenced when the object exists, so if we call it in the static method when the object is not created Non-static member methods are naturally illegal, so the compiler will give an error at this time.

Simply put, a static method can be called without creating an object, and a non-static method must have an instance of the object to be called. Therefore, it is impossible to refer to a non-static method in a static method, because it refers to the non-static method of which object What about the static method? The compiler cannot give an answer, because there is no object, so an error is reported.

class Test 


int a= 6; 

public static void main(String[] args) 
   System.out.print(a);     /** Member variables cannot be called directly (non-static variable a cannot be referenced from a static context)                 */ 
  







As long as it is not a static modified method, it must be referenced by an object. In non-static methods, (this) may be omitted. In the static method, see if there is an object of your class. There is no certain error.

Because the static method is not called through the instance object, there is no this pointer in the static method, and you can't access the non-static variables and methods of the class you belong to. You can only access the local variables in the method body, your own parameters, and static variables. So you must report an error when calling a non-static method in a static main function. So you put the method in another class, create an object and then call it, there will be no error, because your method is not static, that is, it does not belong to the class, but belongs to a specific instance object. Of course, it will not be called with an object. Wrong!

Just remember this:
the members decorated with statci belong to the class, and can be directly called by the class name in the static method;
the members not modified by statci belong to the specific instance object, and need to be called with the object name, and in static The method cannot be called.

Guess you like

Origin blog.csdn.net/liushulin183/article/details/51913398