1.类的初始化顺序 即为 类的静态变量初始化赋值语句和静态块的加载顺序(按出现的先后顺序排列)
2.对象的初始化顺序 即为 ①类的非静态变量的初始化和非静态块的加载顺序(按出现的先后顺序排列)②构造函数
<span style="font-family: Arial, Helvetica, sans-serif;">public class testStatic {
public static int k = print("k"); <span style="white-space:pre"></span> ①
//public static int i = print("i");
public static testStatic t1 = new testStatic("t1"); ②
public static testStatic t2 = new testStatic("t2"); ③
public static int i = print("i"); <span style="white-space:pre"></span> ④
public static int n = 99;
public static int j = print("j"); <span style="white-space:pre"></span> ⑤
public int m = print("m");
{
print("构造块");
}
static{ <span style="white-space:pre"></span> ⑥
System.out.println("!!!!!");
print("静态块");
}
public testStatic(String str){
System.out.println((++k)+":"+str+" i="+i+" n="+n);
++i;++n;
}
public static int print(String str){
System.out.println((++k)+":"+str+" i="+i+" n="+n);
++n;
return ++i;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//testStatic t = new testStatic("init");
}
}</span>
上述类初始化顺序为:①②③④⑤⑥
对应的结果为:①(1)②(2,3,4)③(5,6,7)④(8)⑤(9)⑥(!!!!!和10)
②③静态变量的赋值语句包含了类的初始化操作
结果:
1:k i=0 n=0
2:m i=1 n=1
3:构造块 i=2 n=2
4:t1 i=3 n=3
5:m i=4 n=4
6:构造块 i=5 n=5
7:t2 i=6 n=6
8:i i=7 n=7
9:j i=8 n=99
!!!!!
10:静态块 i=9 n=100