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

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

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();

官网:www.fhadmin.org 继而继续执行,输出为:

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

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

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都是静态变量,它们之间还有个先来后到的次序。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值