这个神奇的题目是这样的。。。
package com.xatu;
public class Text {
public static int k = 0;
public static Text t1 = new Text("t1");
public static Text t2 = new Text("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
{
print("构造块");
}
static {
print("静态块");
}
public Text(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[]) {
Text t = new Text("init");
}
}
平时我们所学习的为,类在加载的时候先加载静态块,再加载实例块,最后加载构造函数。。。可是当类中有好多静态对象的时候还是这样么。。。
这段代码的结果是
1:j i=0 n=0
2:构造块 i=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5:构造块 i=4 n=4
6:t2 i=5 n=5
7:j i=6 n=6
8:构造块 i=7 n=7
9:t3 i=8 n=8
10:i i=9 n=9
11:静态块 i=10 n=99
12:j i=11 n=100
13:构造块 i=12 n=101
14:init i=13 n=102
惊不惊喜,意不意外。
既然这样,我们就debug一下。。。。
debug过程中图太多了,就不一个一个放出来了。。。
在debug过程中,我们发现这段代码就像递归一样,一层接着一层的,看的脑阔疼。
其实这段代码是这样的
至于t1 为什么顺序为(j->构造块->t1)那是因为在对象初始化的时候,实例参数也是按顺序执行的,他会先初始化j又因为j调用了print函数,所以会先打印j然后按照顺序为构造块,最后为t1。
可能会有人问为什么在t1中不加载静态块呢。。。因为静态块只会加载一次。。。而且还没轮到静态块加载,你还在加载t1呢。。。静态变量初始化也是要按照顺序的,如果t1加载静态块,那岂不是t1加载以后还得加载静态的t1,然后。。。emmm无限循环。
所以这段代码可以告诉我们,不管是实例变量,还是静态变量,其初始化都是需要时间,都是具有顺序的,不是并行初始化的。