静态代码块的行为

静态代码块的行为


 1/** 静态块只在类加载时调用一次 */
 2public class StaticBlock {
 3    static int x; // x=0
 4    static {
 5        x += 1;
 6        System.out.println("静态代码块1运行, x= " + x);	// x=1
 7    }
 8    static {
 9        x += 1;
10        System.out.println("静态代码块2运行, x= " + x); // x=2
11    }
12
13    /**
14     * 构造器
15     */
16    StaticBlock() {
17        x++;
18        System.out.println("构造器运行, x= " + x);
19    }
20
21    public static void main(String[] args) {
22        @SuppressWarnings("unused")
23        StaticBlock t = new StaticBlock(); // 调用一次构造器 x=4
24        System.out.println("---------");
25        t = new StaticBlock(); // 调用第二次构造器 , 静态代码块再执行
26
27        System.out.printf("final result of variable x is %s\n", x);
28    }
29
30}
31/**
32静态代码块1运行, x= 1
33静态代码块2运行, x= 2
34构造器运行, x= 3
35---------
36构造器运行, x= 4
37final result of variable x is 4
38 */