初始化顺序
- 基类static block
- 子类static block
- 基类non-static block
- 子类non-static block
- 基类constructor
- 子类constructor
示例代码
1 public class Main {
2 public static void main(String[] args) throws Exception {
3 new Train();
4
5 System.out.println("FINISH!");
6 }
7 }
8
9 class Traffic {
10 public Traffic() {
11 System.out.println("Traffic constructor");
12 }
13 {
14 System.out.println("Traffic non-static block");
15 }
16 static {
17 System.out.println("Traffic static block");
18 }
19 }
20
21 class Train extends Traffic {
22 public Train() {
23 System.out.println("Train constructor");
24 }
25 static {
26 System.out.println("Train static block");
27 }
28 {
29 System.out.println("Train non-static block");
30 }
31 }
Traffic static block
Train static block
Traffic non-static block
Traffic constructor
Train non-static block
Train constructor
FINISH!
static成员的forward reference限制
- 记住这句话:Forward reference is not allowed on the right side of an assignment.