Java code block, static code block and constructor execution order

Today I suddenly remembered a Java interview question I encountered a few years ago. The content is a bit simpler, so I'll record the memo here. I won't discuss deep-level principles.

What is the execution order of code blocks, static code blocks, and constructors in Java?

To solve this problem, consider the inheritance relationship between the parent class and the child class, and consider the sequence of multiple code blocks. So hit the code

father:

public class ParentClass {
    static {
        System.out.println("父类 - 静态 - 代码块1");
    }

    {
        System.out.println("父类 - 普通 - 代码块1");
    }

    static {
        System.out.println("父类 - 静态 - 代码块2");
    }

    public ParentClass(){
        System.out.println("父类 - 构造函数");
    }

    {
        System.out.println("父类 - 普通 - 代码块2");
    }

    static {
        System.out.println("父类 - 静态 - 代码块3");
    }
}

Subclass:

public class SunClass extends ParentClass{
    static {
        System.out.println("子类 - 静态 - 代码块1");
    }

    {
        System.out.println("子类 - 普通 - 代码块1");
    }

    static {
        System.out.println("子类 - 静态 - 代码块2");
    }

    public SunClass() {
        System.out.println("子类 - 构造函数");
    }

    {
        System.out.println("子类 - 普通 - 代码块2");
    }

    static {
        System.out.println("子类 - 静态 - 代码块3");
    }
}

Test category:

public class BlockTest {

    public static void main(String[] args){

        new ParentClass();

        new SunClass();
        new SunClass();


    }

}

Test Results

1. First look at the output of only the new parent class:

父类 - 静态 - 代码块1
父类 - 静态 - 代码块2
父类 - 静态 - 代码块3
父类 - 普通 - 代码块1
父类 - 普通 - 代码块2
父类 - 构造函数

2. Try new two subclasses again:

父类 - 静态 - 代码块1
父类 - 静态 - 代码块2
父类 - 静态 - 代码块3
子类 - 静态 - 代码块1
子类 - 静态 - 代码块2
子类 - 静态 - 代码块3
父类 - 普通 - 代码块1
父类 - 普通 - 代码块2
父类 - 构造函数
子类 - 普通 - 代码块1
子类 - 普通 - 代码块2
子类 - 构造函数
父类 - 普通 - 代码块1
父类 - 普通 - 代码块2
父类 - 构造函数
子类 - 普通 - 代码块1
子类 - 普通 - 代码块2
子类 - 构造函数

in conclusion:

Conclusions can be drawn from the above two tests. When an object is new, the execution order of the code block, static code block, and constructor of the class between the parent and child classes is:

1、父类 - 静态 - 代码块 (多个同级代码块,按照代码顺序执行;且只在类加载时执行一次)
2、子类 - 静态 - 代码块 (多个同级代码块,按照代码顺序执行;且只在类加载时执行一次)

// 第一次 new 
3、父类 - 普通 - 代码块 (多个同级代码块,按照代码顺序执行;在当前类构造函数之前执行;每次 new 时都会执行)
4、父类 - 构造函数
5、子类 - 普通 - 代码块 (多个同级代码块,按照代码顺序执行;在当前类构造函数之前执行;每次 new 时都会执行)
6、子类 - 构造函数

// 第二次 new
7、父类 - 普通 - 代码块 (多个同级代码块,按照代码顺序执行;在当前类构造函数之前执行;每次 new 时都会执行)
8、父类 - 构造函数
9、子类 - 普通 - 代码块 (多个同级代码块,按照代码顺序执行;在当前类构造函数之前执行;每次 new 时都会执行)
10、子类 - 构造函数

 

 

Guess you like

Origin blog.csdn.net/fesdgasdgasdg/article/details/88358810