类中静态代码块、静态属性加载顺序

 1、如果静态属性 在 静态代码块前面

class Foo {
    public Foo() {
        System.out.println("我是 Example 的静态属性 foo ");
        System.out.println("        未修改的静态属性 值为 ====> " + Example.staticVariable);
        Example.staticVariable = 2;
        System.out.println("        修改静态属性 值为 ====> " + Example.staticVariable);
    }
}

class Example {
    static Foo foo = new Foo();
    static int staticVariable = 1;
    static {  
        System.out.println("静态块执行");
        staticVariable = 3;
        System.out.println("        修改静态属性值为===>" + staticVariable);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println( "main方法执行:" + Example.staticVariable);
    }
}

运行结果

放在前面的静态属性先运行 


如果静态代码块 放在前面

class Foo {
    public Foo() {
        System.out.println("我是 Example 的静态属性 foo ");
        System.out.println("        未修改的静态属性 值为 ====> " + Example.staticVariable);
        Example.staticVariable = 2;
        System.out.println("        修改静态属性 值为 ====> " + Example.staticVariable);
    }
}

class Example {
    static int staticVariable = 1;

    // 静态代码块
    static {
        System.out.println("静态块执行");
        staticVariable = 3;
        System.out.println("        修改静态属性值为===>" + staticVariable);
    }
    // 静态属性Foo
    static Foo foo = new Foo();

}

public class Main {
    public static void main(String[] args) {
        System.out.println( "main方法执行:" + Example.staticVariable);
    }
}

运行结果

前面的静态块先运行了 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值