Class Yao ...{
Public static void main (string [] ARGs )...{
System. Out. println ("Yao wants to participate in Olympics ");
}
Static American = new American ();
}
Class American ...{
American ()...{
System. Out. println ("American does not want Yao to participate in the Olympics ");
}
}
Execution result:
American does not want Yao to participate in the Olympic Games
Yao wants to participate in the Olympic Games
The result is as follows:
Yao wants to participate in the Olympic Games
American does not want Yao to participate in the Olympic Games
That's right? What's going on ??
PS: if American = new American (); is placed in main, it is executed sequentially.
Explanation:
During compilation, the program generates the corresponding. Class file for all classes in the code.
During execution, the program loads all. class files (including the. Class file imported by import and the parent class. Class file inherited by extends ).
Then optimization is performed. This is why the first running is slow and will be fast in the future.
After all this is done, the program initializes the static member (variable, object or object reference ), it is necessary to ensure that all variables and references must be initialized when used. Of course, static members must be initialized first.
Initializing static members is a specific method for Java to implement this guarantee.
Of course, not all static variables in the class are initialized for the first time. For static variables or object references in a separate class, they are initialized only when, for example, the new one.
Initialize the constructor only after static Initialization is complete. Use the default constructor or the constructor that you overwrite.
In this example, because the Yao class has a static reference variable, the static reference is initialized first.
However, this is a new American class, and there is no static member in this class, so the constructor American () {} is called to initialize the American
After all the operations are completed, the output in the main method is performed. Therefore, the result is...
PS: For code static American = new American ();
New American () error: heap memory cannot be defined directly in the method body. stack memory reference is required (syntax error on token "new", delete this token ).
American = new American () is good, but there is a bug: the reference of American is non-static, so it is impossible to call the construction method of American class when no object is created.
So we can change it to static American = new American (); To println "American does not want Yao to participate in the Olympics ".
Here is another example:
Class shunxu ...{
Public static void main (string [] ARGs )...{
Int A = 1;
System. Out. println ("A =" + A + "; B =" + B); // error: B cannot be resolved
Int B = 2;
}
}
Class shunxu2 ...{
Static int A = 1;
Public static void main (string [] ARGs )...{
System. Out. println ("A =" + A + "; B =" + B );
}
Static int B = 2;
}