# 普通代码块

代码块(code block): 通常指由{}所包围的一块代码

普通代码块可以用于对复杂或较长的方法进行切割分块,防止变量名冲突(不常用)

public void test() {
    {
        int num = 1;
    }
    {
        int num = 10;
    }
}
1
2
3
4
5
6
7
8

# 构造代码块

构造代码块(Instance Initialization Block)通常放置于构造器代码前,在实例创建时执行,且在构造器之前执行

class Test {
    {
        System.out.println("IIB Block1");
    }
    {
        System.out.println("IIB Block2");
    }
    Test() {
        System.out.println("Constructor Called");
    }
}

/* Output
 * IIB Block1
 * IIB Block2
 * Constructor Called
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 静态代码块

静态代码块(Static Block)是由static修饰的代码块,通常用于静态初始化
只在该类第 1 次被实例化或第 1 次访问该类的静态成员时执行 1 次(即加载进内存时),先于构造块

静态代码块执行,晚于,静态属性的赋值,即 x 最终值为 2

class Test {

    static int x = 1;

    static {
        x = 2;
        System.out.println("Static Block");
    }
    {
        System.out.println("IIB Block");
    }
    Test() {
        System.out.println("Constructor Called");
    }
}

/* Output
 * Static Block
 * IIB Block
 * Constructor Called
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 同步代码块

Java多线程编程

# 参考

[1] 阿里云大学 | 李兴华 - Java语言基础 (opens new window)

Last Updated: 9/24/2020, 8:12:29 AM