Java Initialization Order
1 The class is loaded first when you start an instance of new B. (Classes are loaded by the Java class loader only when they are created with the new call)
2, when loading the class, first load the parent class A, and then load the subclass B
3, after loading the parent class A, complete the static action (including static code and variables, their levels are the same, initialization occurs in the installation code)
4, after loading sub-Class B, complete the static action
Class mount complete, start instantiation
1, when instantiating subclass B, first instantiate the parent class A
2, the member instantiation (non-static code) when the parent class A is instantiated
3, the construction method of parent Class A
4, member instantiation of subclass B (non-static code)
5, the construction method of sub-class B
Initializes the static code of the parent class---> initializes the static code of the subclass--initializes the non-static code of the parent class---> initializes the parent class constructor---> initializes the subclass non-static code---> initializes the subclass constructor
Test code:
abstract class base
{
public int age = getNumber (100);
static {
System.out.println ("base static block");
}
{
System.out.println ("base nonstatic block");
}
static int sage = getNumber (50);
base () {
System.out.println (age);
System.out.println ("base start");
draw (); // The method overridden by the subclass will be called, here is 0!
System.out.println ("base end");
}
static int getNumber (int base) {
System.out.println ("base.getNumber int" + base);
return base;
}
public void draw () {
System.out.println ("base.draw");
}
}
public class initializeOrder extends base {
public int age = getNumber (1001);
private int _radius = getNumber (10);
static int sage = getNumber (250);
static {
System.out.println ("subclass static block");
}
{
System.out.println ("subclass nonstatic block");
}
initializeOrder (int radius) {
_radius = radius;
System.out.println (age);
draw (); // here is 1000
System.out.println ("initializeOrder initialized");
}
public void draw () {
System.out.println ("initializeOrder.draw" + _radius);
}
public static void main (String [] args) {// TODO Auto-generated method stub
new initializeOrder (1000);
}
}
The output is:
Base static block
Base.getnumber Int50
Base.getnumber int250
Subclass Static Block
Base.getnumber int100
Base nonstatic block
100
Base Start
Initializeorder.draw 0
Base End
Base.getnumber int1001
Base.getnumber int10
Subclass Nonstatic Block
1001
Initializeorder.draw 1000
Initializeorder initialized
Go Summary of Java initialization sequence-static variables, static code blocks, member variables, constructors