A non-static method (without static) can access static methods (with static), but not in the opposite way, why not?
public class test{public void static main (String args[]) {method ();//error, prompting you to change method to static method2 ();//Call method 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 is to be analyzed from the memory mechanism of Java, first, when you new an object, not first in the heap to open up memory space for the object, but first the static method in the class (static function with static modifier) loaded into a place called the method area, and then create the object in the heap memory. Therefore, static methods are loaded as the class loads. When you new an object that exists in memory, the This keyword generally refers to the object, but it is also possible to invoke the static method of the class with the class name without the new object.
The program is ultimately executed in memory, the variables are accessed only in memory, the static members of the class (Metamorphosis and methods) belong to the class itself, when the class is loaded with memory, can be directly accessed through the class name, non-static members (variables and methods) belong to the object of the class, So the memory is allocated only when the class object is created, and then accessed through the object of the class.
Accessing a non-static member in a static member of a class can be an error because a static member already exists when the non-static member of the class does not exist, and accessing something that does not exist in memory is of course an error.
When did the class get loaded? is loaded when a call is required.
Why a Java static method cannot access a non-static method