下面是Think in Java中的一段代碼,自己加了幾行
package reusing;
import static net.mindview.util.Print.*;
class Insect {
private int i = 9;
protected int j;
private int x2 = printInit("Insect.x1 initialized");
Insect() {
print("i = " + i + ", j = " + j);
j = 39;
}
static {
System.out.println("Init Static block");
}
{
System.out.println("Init block");
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s) {
print(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInit("Beetle.k initialized");
static {
System.out.println("Beetle static block");
}
public Beetle() {
print("k = " + k);
print("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
private int x1 = printInit("Beetle.x2 initialized");
public static void main(String[] args) {
print("Beetle constructor");
Beetle b = new Beetle();
}
}
分析其類加載的過程:
(1)首先加載當前類,再加載當前類的父類,直到加載到基類,然後執行基類的static代碼塊,再執給基類裡面的static成員變量賦值,賦值完成之後再執行子類裡面的static代碼塊和給static成員變量賦值,以此類推。
(2)static塊和成員賦值為完成之後回到基類中,給其余的非static的成員變量賦值,再執行非靜態塊,然後是構造方法,完成之後回到子類中繼續按(2)處執行
上面的代碼執行結果是:
Init Static block
static Insect.x1 initialized
Beetle static block
static Beetle.x2 initialized
Beetle constructor
Insect.x1 initialized
Init block
i = 9, j = 0
Beetle.k initialized
Beetle.x2 initialized
k = 47
j = 39