Easy to view the initialization order, using the following print class
public class print {public Print (String str) {System.out.println (str);}}
This article discusses the initialization order of classes in two cases, namely, the initialization of individual classes, and the initialization of classes with inherited Relationships.
1. Initialization of individual classes
Take the following code as an example
public class Father {static {System.out.println ("Father Static code block");} public static Print Fatherstaticprint = new print ("Father static variable");p ublic print Fatherprint = new print ("Father non-static variable");p UBL IC Father () {System.out.println ("Father constructor");} @Overrideprotected void Finalize () throws Throwable {super.finalize (); System.out.println ("Father destructor");}}
Class in the main function
public static void main (String Args[]) {Father Father = new Father (); System.runfinalizersonexit (true); }
The results of the execution are as follows
If you change the static code block and the static variable position of the Father class, as shown below
public class Father {public static Print fatherstaticprint = new print ("Father static variable"), static {System.out.println ("Father static State code block ");} Public print Fatherprint = new print ("Father non-static variable");p ublic Father () {System.out.println ("Father constructor");} @Overrideprotected void Finalize () throws Throwable {super.finalize (); System.out.println ("Father destructor");}}
Then the result of execution becomes
It is therefore possible to conclude that static code blocks and static variables have the same precedence, and who is first Initialized.
The exact process is as Follows:
2. Initialization of a class with an inheritance relationship
Take the following class as an example
public class Son extends Father {static {System.out.println ("son Static code block");} public static Print Sonstaticprint = new print ("son static variable");p ublic print Sonprint = new print ("son non-static variable");p ublic son () {Sys Tem.out.println ("Son constructor");} @Overrideprotected void Finalize () throws Throwable {super.finalize (); System.out.println ("Son destructor");}}
The class son inherits the class father, initializes the son in the main function, and executes the result as follows
therefore, The following conclusions can be drawn:
Initialization Order of Java classes