This article discusses the execution order of (static) variables and (static) code blocks in Java by first creating 3 classes: 1, Foo class, for printing variables
Public class Foo { public Foo (String word) { System.out.println (word); }}
2. Parent class
Public class Parent { staticnew Foo ("Parent ' s static parameter"); New Foo ("Parent ' s parameter"); Static { System.out.println ("Parent ' s Static code block"); } { System.out.println ("Parent ' s code block"); } Public Parent () { System.out.println ("parent.parent ()");} }
3. Child class
Public class extends parent{ staticnew Foo ("child ' s static parameter"); New Foo ("Child ' s Parameter"); Static { System.out.println ("Child ' s static code block"); } { System.out.println ("Child ' s code block"); } Public Child () { System.out.println ("Child.child ()");} }
Next Run the instance:
Public class Run { publicstaticvoid main (string[] args) { new Child (); }}
Printing results:
Parent's static parameterparent's static code blockchild ' s static parameterchild ' s static code blockparent ' s Parameterpar ENT's code blockparent.parent ()child's Parameterchild ' s Code blockchild.child ()
Summarize
Static variables and static blocks of code in Java are executed when the class is loaded, and when the object is instantiated, the variable is declared and instantiated before the constructor is executed. If the subclass inherits the parent class, the static and static code blocks of the parent class are executed first, and then the static and static code blocks of the subclass are executed. Again, the parent class and subclass non-static code blocks and constructors are executed.
Note: (Static) variables and (static) blocks of code are also in order of execution, consistent with the order in which the code is written. (static) variables can be used in (static) code blocks, but used (static) variables must be declared before (static) blocks of code.
Finally, the following steps are given:
1, the parent class static variables and static code blocks (first declared first execution);
2, sub-class static variables and static code block (first declared first execution);
3, the parent class variable and code block (first declares first executes);
4, the parent class constructor;
5, sub-class variables and code blocks (first declared first execution);
6, the constructor of the child class.
Execution order of Java (static) variables and (static) code blocks