Java类初始化顺序

顺序介绍

  1. Parent的static块
  2. Son的Static块
  3. Parent的初始化块
  4. Parent的构造函数
  5. Son的构初始化块
  6. Son的构造函数

Demo

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
public class D {
private int age;
private String name;
public D(int age,String name) {
System.out.println("执行构造器");
this.age=age;
this.name=name;
}
static{
System.out.println("静态初始化块");
}
{
System.out.println("执行非静态初始化块");
weight=2.0;
}
//定义时指定初始值
double weight=2.3;
@Override
public String toString() {
return "TestField [age=" + age + ", name=" + name + ", weight="
+ weight + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
D tf=new D(22, "KITTY");
System.out.println(tf);
D tf2=new D(30, "tom");
System.out.println(tf2);
}
}

执行结果

1
2
3
4
5
6
7
静态初始化块
执行非静态初始化块
执行构造器
TestField [age=22, name=KITTY, weight=2.3]
执行非静态初始化块
执行构造器
TestField [age=30, name=tom, weight=2.3]

weight=2.3 ?

1
2
3
4
5
.....
weight=2.0
.....
double weight=2.3;
.....

处执行顺序为:

  1. double weight
  2. weight = 2.0(此语句在前面先执行)
  3. weight = 2.3