關於初始化及初始化順序

成員變量的自動初始化

首先,類的成員變量會被自動初始化,並且會在構造器被調用前發生,如下:

public class TestInitialization {
    //成員變量i
    private int i;

    public TestInitialization() {
        System.out.println(i);//輸出0,說明在i被聲明時被初始化爲0
        System.out.print(i++);//輸出1
    }

    public static void main(String[] args) {
        new TestInitialization();
    }

}

靜態數據的初始化順序

代碼如下:

//主類
public class StaticInitialization {

    public static void main(String[] args) {
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        table.f2(1);
        cupboard.f3(1);
    }

    //調用main之前,順序初始化兩個靜態實例
    //若存在非靜態引用,則在靜態引用被初始化後,繼續初始化非靜態引用
    static Table table = new Table();

    static Cupboard cupboard = new Cupboard();

}

//bowl
class Bowl {

    Bowl(int marker) {
        System.out.println("Bowl(" + marker + ")");
    }

    void f1(int marker) {
        System.out.println("f1(" + marker + ")");
    }

}

//table
class Table {

    static Bowl bowl1 = new Bowl(1);

    Table() {
        System.out.println("Table()");
        bowl2.f1(1);
    }

    void f2(int marker) {
        System.out.println("f2(" + marker + ")");
    }

    static Bowl bowl2 = new Bowl(2);

}

//cupboard 
class Cupboard {

    //靜態引用bowl4、bowl5初始化後,初始化bowl3
    Bowl bowl3 = new Bowl(3);

    static Bowl bowl4 = new Bowl(4);

    Cupboard() {
        System.out.println("Cupboard()");
        bowl4.f1(2);
    }

    void f3(int marker) {
        System.out.println("f3(" + marker + ")");
    }

    static Bowl bowl5 = new Bowl(5);

}

輸出如下:

Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)

未完,待整理。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章