Why can't Java static methods be accessed?
Non-static methods (without static) can access static methods (with static), but in turn won't work. Why?
Public class test {public void static main (String args []) {method (); // an error occurs. You are prompted to change the method to the static method2 (); // The call method is correct. new Test2 (). method (); // correct} public void method () {System. out. println ("HelloWorld");} public static void method2 () {System. out. println ("HelloWorld") ;}} public class Test2 {public void method () {System. out. println ("HelloWorld ");}}
This should be analyzed from the memory mechanism of java. First, when you create an object, it does not first open up memory space for the object in the heap, instead, load the code of the static method (static function with static modification) in the class to a place called the method area, and then create an object in the heap memory. Therefore, static methods will be loaded with the loading of classes. When you create an object, the object exists in the memory. The this keyword generally refers to this object. However, if there is no new object, you can call the static method of this class through the class name.
The program is eventually executed in the memory. variables are accessed only when they have a place in the memory. The static members of the class (abnormal and method) belong to the class itself, when a class is loaded, the memory is allocated and can be accessed directly using the class name. Non-static members (variables and methods) are class objects, therefore, the memory is allocated only when the class Object Zen master (creates an instance), and then accessed through the class object.
An error occurs when a static member of a class accesses a non-static member because the static member already exists when the non-static member of the class does not exist, an error occurs when accessing something that does not exist in the memory.
When is the class loaded? It is loaded when it needs to be called.