本類中的初始化順序
public class A {
private int a = show(1);
static{
System.out.println("static A");
}
public A(){
System.out.println("A--無參構造器");
}
private int show(int i2) {
System.out.println("A:"+i2);
return i2;
}
public static void main(String[] args) {
A a = new A();
}
}
//輸出結果爲:
//static A
//A:1
//A--無參構造器
由程序的運行結果可知一個類中的初始化順序爲:
- 靜態方法或靜態塊(它們之間沒有優先順序,以實際出現的順序爲準)。
- 非靜態代碼(變量或代碼塊)
- 構造方法
子父類中的初始化順序
public class A {
private int a = show(1);
static{
System.out.println("static A");
}
public A(){
System.out.println("A--無參構造器");
}
private int show(int i2) {
System.out.println("A:"+i2);
return i2;
}
}
public class B extends A{
private int a = show(2);
static{
System.out.println("static B");
}
public B(String name){
System.out.println("B--有參構造器:"+name);
}
private int show(int i2) {
System.out.println("B:"+i2);
return i2;
}
public static void main(String[] args) {
B b1 = new B("b1");
}
}
//執行結果爲:;
//static A
//static B
//A:1
//A--無參構造器
//B:2
//B--有參構造器:b1
由上例可知在存在繼承關係的類的初始化的順序爲:
- 父類的靜態代碼
- 子類的靜態代碼
- 父類的非靜態代碼
- 父類的構造器
- 子類的非靜態代碼
- 子類的構造器
一道經典的關於初始化順序的面試題
public class Test {
public static int k=0;
public static Test t1=new Test("t1");
public static Test t2=new Test("t2");
public static int i=print("i");
public static int n=99;
private int a=0;
public int j=print("j");
{
print("構造塊");
}
static
{
print("靜態塊");
}
public Test(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[])
{
Test t=new Test("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:i i=6 n=6
8:靜態塊 i=7 n=99
9:j i=8 n=100
10:構造塊 i=9 n=101
11:init i=10 n=102
分析執行過程:
1.加載public static int k=0;
2.加載public static Test t1=new Test(“t1”);這時需要實例化t1,因此下一步要執行非靜態代碼和構造器。
3.加載private int a=0;
4.加載public int j=print(“j”);
5.加載public static int print(String str) 這個方法。
6.加載構造器public Test(String str)
7.加載public static Test t2=new Test(“t2”); 重複2-6步
8.繼續加載類的靜態屬性。加載public static int i = print(“i”);並執行完畢。
9.繼續加載類的靜態屬性。加載public static int n=99;
10.加載主函數,加載Test t=new Test(“init”);
11.重複2-6步直至結束。
這道題十分考驗基礎而且還沒涉及繼承的情況,現在我只從表面理解初始化順序,相信將來研究了JVM的初始化原理,就能更深入的理解它。