Problem resolution

public class Test
{
    public static Test t1 = new Test();
    {
         System.out.println("blockA");
    }
    static
    {
        System.out.println("blockB");
    }
    public static void main(String[] args)
    {
        Test t2 = new Test();
    }
 }

答案: blockA blockB blockA

The first difference is the class initialization, the instance initialization

Class loading preparation stage -> class initialization clinit stage

Class loading preparation stage: variables are assigned initial values ​​required by the system (0 or null, etc.), final variables will be assigned user-defined initial values ​​at this time

Class initialization process:

Step1 The compiler collects assignment actions of t1, static statement block, main method statement block

Step2 Execute the collected statement block:

Step2.1 Execute t1 = new Test, find that the clinit process has been called, so you can start to trigger the init process, perform the initialization of member variables (not here), and the non-static code block, output blockA, and finally call the constructor (not here )

Step2.2 According to the order, execute the static statement block and output blockB

Step2.3 According to the order, execute the main method statement block, execute t2 = new Test, trigger the init method, execute the non-static code block, and output blockA

Guess you like

Origin blog.csdn.net/qq_37669050/article/details/100712142