面试题-代码执行顺序

例1

public class LeafTest {

    public static void main(String[] args) {
        new Leaf();
    }
}

class Root{
    static {
        System.out.println("root static block");
    }

    {
        System.out.println("root block");
    }
    Root(){
        System.out.println("root default constructor");
    }
}
class Mid extends Root{
    static {
        System.out.println("Mid static block");
    }

    {
        System.out.println("Mid block");
    }
    Mid(){
        System.out.println("Mid default constructor");
    }
}
class Leaf extends Mid{
    static {
        System.out.println("Leaf static block");
    }

    {
        System.out.println("Leaf block");
    }
    Leaf(){
        System.out.println("Leaf default constructor");
    }
}

显示结果

root static block
Mid static block
Leaf static block
root block
root default constructor
Mid block
Mid default constructor
Leaf block
Leaf default constructor

先父类,后子类。静态先行

例2

public class A extends B{
    static {
        System.out.println("1111");
    }
    {
        System.out.println("2222");
    }
    A(){
        System.out.println("3333");
    }
    public static void main(String[] args) {
        System.out.println("4444");

        System.out.println("#####");
        new A();
        System.out.println("$$$$");
        new A();
        System.out.println("****");
        new B();
    }
}
class B{
    static {
        System.out.println("5555");
    }
    {
        System.out.println("6666");
    }
    B(){
        System.out.println("7777");
    }

}

显示结果

5555
1111
4444
#####
6666
7777
2222
3333
$$$$
6666
7777
2222
3333
****
6666
7777

推荐阅读更多精彩内容