java class variable initialization order

Suppose there is a class defined as follows:

package com.zhang;

public  final  class Girl {
     // static code block 1 
    private  static String sex = "female" ;
     // member method code block 1 
    private String name = "anonymous" ;
    
    // static code block 2 
    static {
        System.out.println("static1");
    }
    
    // Member method code block 3 
    public Girl() {
        System.out.println("constructor");
    }
    
    // static code block 3 
    static {
        System.out.println("static2");
    }
    
    // Member method code block 2 
    private  int age = 18 ;
}

When a class is loaded for the first time and an object of this class is created, what is the initialization order of static variables and member variables, and what is the execution order of static code?

Create a class object. If the class is not initialized, first initialize the class (execute the clinit method), and then execute the constructor (init method), specifically, execute the static code block in the class file first, and then execute the constructor code block. . Observe the class file static code block of the above class:

It can be seen that the content of the static code block is that the static statements are collected in order, and the assignment of static variables is also a static statement. The pseudo code is as follows:

static {
    sex = "female";
    System.out.println("static1");
    System.out.println("static2");
}

Constructor code block:

The corresponding pseudocode is as follows:

public Girl() {
<init> name
= "anonymous"; age = 18; System.out.println("constructor"); }

The <init> method is executed first, that is, the statements outside the constructor are collected in order, and then the statements within the constructor are executed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324586449&siteId=291194637