Preface:

The order in which Static code blocks are executed should be one of the most important questions for an interviewer.

Let’s write some code to analyze the execution order:

Calling code:

public class Client { public static void main(String[] args) { Son son = new Son(); son.running(); }}Copy the code

The parent class:

Public class Father {static {system.out.println (" static "); "); } {system.out. println(" parent common code block..." ); } //static String constant; Public Father() {system.out.println (" parent constructor... ); } public void running() { System.out.println("I'm Running Method..." ); }}Copy the code

The subclass:

Public class extends Father {static {system.out.println (" static "); ); } {system.out. println(" Subclass plain code block..." ); } public Son() {system.out.println (" subclass constructor... ); }}Copy the code

Its running results:

The above is the result of a subclass inheriting the parent class, and its execution order is as follows:

Superclass Static code Block – > Subclass Static code Block – > Superclass common code Block – > Superclass Constructor – > Subclass Common code Block – > Subclass Construction

Thus, there is no inherited class, which is executed in the following order:

Static code block – > plain code block – > class constructor;

Static code block call sequence; Static code block call sequence