Java中static块,构造块,构造函数的执行顺序

public class Father {
    static {
        System.out.println("Father静态块");
    }

    {
        System.out.println("Father构造块");
    }

    public Father() {
        System.out.println("Father构造器");
    }

    void func1() {
        System.out.println("Father方法 1");
    }

    public static void main(String[] args) {
        Father father = new Son();
        father.func1();
    }

}

class Son extends Father {
    static{
        System.out.println("Son静态块");
    }

    {
        System.out.println("Son构造块");
    }

    public Son() {
        System.out.println("Son构造器");
    }

    @Override
    void func1() {
        System.out.println("Son方法 1");
    }

    void func2() {
        System.out.println("Son方法 2");
    }

}

结果:

Father静态块
Son静态块
Father构造块
Father构造器
Son构造块
Son构造器
Son方法 1

猜你喜欢

转载自www.cnblogs.com/convict/p/9932804.html