Java代码块运行顺序

Java代码运行顺序

类内容(静态变量、静态初始化块) > 实例内容(变量、初始化块、构造器)
{static变量、static{}} > {初始变量、初始化块{} > ClassName{}> NormalFunction(){}}

static{}:从属于类的方法,在有类的,还没有类对象的时候即存在了
初始化代码块{}: 初始化类对象优先运行代码块,再运行构造方法
ClassName(){}: 对象构造方法,初始化对象运行
NormalFunction(){}: 最后运行

static变量和static{}按照顺序决定代码前后顺序输出结果
普通变量 初始化代码块{} 构造方法:

  • 普通变量 初始化代码块{} 按照顺序决定代码前后顺序输出结果
  • 有构造方法的话,因为构造方法是最后运行的,所以按照构造方法的结果输出

代码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package source.file.TestStatic;

public class Test{


Test(){
System.out.println("construct code block");
// j = 3;
}

// 输出结果为j = 1
// {
// System.out.println("unflagged code block");
// j = 3;
// }
// int j = 1;

// 输出结果为 j= 2
int j = 1;
{
System.out.println("unflagged code block");
j = 2;
}



// 输出结果为i = 20
// static{
// System.out.println("static code block");
// i = 30;
// }
// static int i = 20;


// 输出结果为i = 30
static int i = 20;
static{
System.out.println("static code block");
i = 30;
}


public void codeBlock(){
System.out.println("normal function code block");
}

public static void main(String[] args) {
Test t = new Test();
t.codeBlock();

Test t2 = new Test();
t2.codeBlock();
System.out.println(Test.i);
System.out.println(t2.j);
}
}

运行结果

1
2
3
4
5
6
static code block
unflagged code block
construct code block
normal function code block
unflagged code blockconstruct code block
normal function code block

Java代码块运行顺序
http://oowatermelon.github.io/OoWaterMelonS/2022/10/06/Java代码块运行顺序/
作者
OoWaterMelonS Shao
发布于
2022年10月6日
许可协议