How does Java access an instance member of a class in a static method (a field or method with no static keyword attached)?
Static modifiers are loaded at load time before non-static loading, that is, if a non-static method or variable is called in static, the non-static methods and variables do not exist at this time (this can be understood) .
Accessing an instance variable of a class in a static method requires first instantiating the class, and in addition to the static modification, you can first create an object that invokes the member methods and variables through the object, such as new A (). Test ().
For example:
Packagestatic methods access instance variables; Public classtest{intA = 2;//instance Variable Static intb = 3;//Static variables of the class Public Static voidVariable ()//Static Methods{System.out.println ("Instance variable a =" +NewTest (). a); //accessing an instance variable of a class in a static method requires first instantiating the classSystem.out.println ("Static variable B =" +b); //Static variables of a class can be accessed directly in a static method } Public Static voidMain (string[] args) {test.variable (); Test test=NewTest (); System.out.println ("The result is: instance variable =" + test.a);//Accessing Instance members } }
The result is:
How Java accesses instance members of a class in a static method (a field or method with no static keyword attached)