/**
* Created by xfyou on 2016/11/2.
* Java继承的初始化
*/
public class Beetle extends Insect {
int k = prt("Beetle.k initialized");
public Beetle() {
prt("k = " + k);
prt("j = " + j);
}
static int x2 = prt("static Beetle.x2 initialized");
static int prt(String s) {
System.out.println(s);
return 63;
}
public static void main(String[] args) {
prt("Beetle constructor");
Beetle b = new Beetle();
}
}
class Insect {
int i = 9;
int j;
public Insect() {
prt("i = " + i + ", j = " + j);
j = 39;
}
static int x1 = prt("static Insect.x1 initialized");
static int prt(String s) {
System.out.println(s);
return 47;
}
}
执行结果如下:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 63
j = 39
执行顺序总结:
1、父类静态字段
2、父类静态初始化块
3、子类静态字段
4、子类静态初始化块
5、父类实例字段
6、父类实例初始化块
7、父类构造器
8、子类实例字段
9、子类实例初始化块
10、子类构造器
没有继承的单个类的初始化顺序为:
- 静态字段
- 静态初始化块
- 实例字段
- 实例初始化块
- 构造器