静态代码块、非静待代码块、静态变量的执行次序

关于静态代码块、非静待代码块、静态变量的执行次序,大的问题相信大家都明白,但是最近有同学问到了如下问题,觉得难以理解其输出。其问题的代码如下:

public class StaticTest {

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

    static StaticTest st = new StaticTest();
    static {
        System.out.println("1");
    }
    {
        System.out.println("2");
    }

    public StaticTest() {
        System.out.println("3");
        System.out.println("a=" + a + " b=" + b);
    }

    private static void staticFunction() {
        System.out.println("4");
    }

    int a = 100;
    static int b = 112;

}

其输出为:

2
3
a=100 b=0
1
4

其实,任何问题碰到了,我们的首要任务是分解,就像上面这段代码,我们首先把这行代码注释掉:

//static StaticTest st = new StaticTest();

继而继续执行,输出为:

1
4

这个很好理解,如果类被用到,静态代码块会首先被执行,所以一般来说,静态代码块被用作与类变量(静态变量)的初始化。

接下来,我们先不分析上面的代码,先看一段其它的代码:

public class StaticTest {
    public static void main(String[] args) {
    }
    static Test01 test01 = new Test01();
}

class Test01{
    static int b = 112;
    public Test01(){
        System.out.println( "b=" + b);
    }
}

输出为多少,你一定会说,是:

b=112

完美,我们的理解没错,但是,仿佛最上面的代码就不对了,我们还原下最上面的代码:

public class StaticTest {
    public static void main(String[] args) {
    }
    public StaticTest(){
        System.out.println( "b=" + b);
    }
    static StaticTest test01 = new StaticTest();
    static int b = 112;
}

输出为:

b=0

我觉得如果这个时候我们还不能理解的话,我们稍稍改变下代码的位置:

static int b = 112;
static StaticTest test01 = new StaticTest();

输出结果为112;

所以把最开始的那段代码中b的定义移到st的上面一行,

static int b = 112;
static StaticTest st = new StaticTest();

输出就变为:

2
3
a=100 b=112
1
4

因为b和st都是静态变量,它们之间还有个先来后到的次序。

剩下的,应该都是很好理解的了。

猜你喜欢

转载自blog.csdn.net/luminji/article/details/76966379
今日推荐