From: http://lehsyh.javaeye.com/blog/569674
Corrected an error in the original article.
Class Parent {
Static string name = "hello ";
Static {
System. Out. println ("parent static block ");
}
{
System. Out. println ("parent block ");
}
Public parent (){
System. Out. println ("parent constructor ");
}
}
Class Child extends parent {
Static string childname = "hello ";
Static {
System. Out. println ("Child static block ");
}
{
System. Out. println ("Child block ");
}
Public Child (){
System. Out. println ("Child constructor ");
}
}
Public class staticiniblockordertest {
Public static void main (string [] ARGs ){
New Child (); // Statement (*)
}
}
Q: When the statement (*) is executed, what is the order of the printed results? Why?
A: When the statement (*) is executed, the print result is in the following order: parent static block, child static block, parent block, parent constructor, child block, and child constructor.
Object initialization sequence:
Parent class static-> subclass static-> parent class default {}-> parent class constructor-> subclass default {}-> subclass Constructor
First, the static content of the parent class is executed. After the static content of the parent class is executed, the static content of the Child class is executed. After the static content of the Child class is executed, check whether the parent class has non-static code blocks. If yes, execute the non-static code blocks of the parent class. After the non-static code blocks of the parent class are executed, execute the construction method of the parent class; after the constructor of the parent class is executed, it goes on to check whether the Child class has non-static code blocks. If so, it executes the non-static code blocks of the Child class. The non-static code block of the subclass is executed before the subclass constructor is executed.
In a word,The content of the static code block is first executed, followed by the non-static code block and constructor of the parent class, and then the non-static code block and constructor of the subclass are executed.
Note: No matter whether the constructor includes any parameter or not, the constructor of the subclass first searches for the constructor without parameters of the parent class.If the parent class does not have a constructor without parameters, the Child class must use the super key to call the constructor with parameters in the parent class. Otherwise, the compilation fails.
PS:
1) in a static method, only other static members (including variables and methods) of the same type can be called directly, rather than non-static members in the category.
2) static variables belong to the entire class instead of an object. Note that no variable in the method body can be declared as static.
3) When a class is loaded, the static code block is executed only once. Static blocks are often used to initialize class attributes. For example:
Static
{
}