静态块 非静态块 构造器 执行的顺序

时间:2023-02-02 19:35:31

顺序:

父类静态块 > 子类静态块 > 父类 非静态块 > 父类构造器 >  子类非静态块 > 子类构造器。

Example:

public class BlockParentTest {

    public BlockParentTest() {
        System.out.println("parent constructor");
    }
    
    static {
        System.out.println("parent static block");
    }
    
    {
        System.out.println("parent block");
    }
}
public class BlockTest extends BlockParentTest{

    public BlockTest() {
        System.out.println("child constructor");
    }
    
    {
        System.out.println("child block");
    }
    
    static {
        System.out.println("child static block");
    }
    public static void main(String[] args) {
        new BlockTest();
    }
}

Result:

parent static block
child static block
parent block
parent constructor
child block
child constructor