java面试 3. java中 static 相关

问题引入:

eg1:

public class StaticTest {

    // ①
    private static StaticTest st = new StaticTest();

    // ②
    public static int count1;

    // ③
    public static int count2 = 0;

    // ④
    private StaticTest(){
        count1++;
        count2++;
    }

    // ⑤
    public static StaticTest getInstance(){
        return st;
    }

    public static void main(String[] args) {
        // ⑥
        StaticTest st = StaticTest.getInstance();
        System.out.println("count1: " + count1);
        System.out.println("count2: " + count2);
    }
}

// output
count1: 1
count2: 0

结果分析:执行顺序:①-> ④(初始化 ② ③) -> ③( 因为有显式赋值,所以顺序执行之后并赋值 ) -> ⑥ -> ⑤;所以 count1 和 count2 最初初始化都为 0,执行完 StaticTest()  方法之后都变为 1,接着由于 ② 中没有显式赋值,此时依然为 1,而最后又执行到 ③ 时,由于有显式赋值,所以 count2 又被赋值为 0,所以最后的结果就变成了 1 和 0。

eg2:

public class StaticTest {
    // ①
    public static int count1;

    // ②
    public static int count2 = 0;

    // ③
    private static StaticTest st = new StaticTest();

    // ④
    private StaticTest(){
        count1++;
        count2++;
    }

    // ⑤
    public static StaticTest getInstance(){
        return st;
    }

    public static void main(String[] args) {
        // ⑥
        StaticTest st = StaticTest.getInstance();
        System.out.println("count1: " + count1);
        System.out.println("count2: " + count2);
    }
}

// output
count1: 1
count2: 1

结果分析:执行顺序: ① -> ② -> ③ -> ④ -> ⑥ -> ⑤;所以最后结果为 1 和 1。

综上:static 修饰的变量、静态代码块等是在类加载时进行顺序执行的,也就是类执行之前完成的。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值