程序员

Static初始化函数、构造函数的执行顺序

2017-07-06  本文已影响0人  DeppWang

我相信很多人对下面这段代码输出什么都不是特别明白,包括原来的我,特写出来分享。

class StaticSuper{
    static{
        System.out.println("super static block");
    }

    StaticSuper(){
        System.out.println("super constructor");
    }
}

public class StaticSuperTest extends StaticSuper{
    static{
        System.out.println("static  block");
    }

    StaticSuperTest(){
        System.out.println("constructor");
    }

    public static void main(String[] args){
        System.out.println("in main");
        StaticSuperTest s = new StaticSuperTest();
    }
}

答案是:

super static block
static  block
in main
super constructor
constructor

static初始化函数(static initializer)是一段在加载类时会执行的程序代码,它会在其他程序可以使用该类之前就执行看,具体说,static初始化函数是由类调用的。类调用时,先执行static初始化函数,然后才执行主函数的。

构造函数的作用是用于给对象进行初始化。不建立对象,构造函数时不会运行的。

运行过程如下:

参考资料

Java提高篇——静态代码块、构造代码块、构造函数以及Java类初始化顺序

上一篇 下一篇

猜你喜欢

热点阅读