類的初始化和創建過程

楔子

菜鳥的學習筆記。

《On Java 8》中文版

類的初始化

以Dog的類概括一下創建對象的過程

  1. 即使沒有顯示地使用static關鍵字,構造器實際上也是靜態方法。所有,當首次創建Dog 類型的對象或是首次訪問Dog類的靜態方法或屬性時,Java解釋器必須在類路徑中查找,以定位Gog.class
  2. 當加載完Dog.class後,有關靜態初始化的所有動作都會執行。因此,靜態初始化只會在首次加載Class對象時初始化一次。
  3. 當用new Dog()創建對象時,首先會在堆上爲Dog對象分配足夠的存儲空間。
  4. 分配的存儲空間首先會被清零,即會將Dog對象中的所有基本類型數據設置爲默認值(數字會被置0,布爾型和字符型也相同)。引用被置爲null。
  5. 執行所有出現在字段定義出的初始化動作。
  6. 執行構造器。

類初始化

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

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

class Table {


    static Bowl bowl1 = new Bowl(1);
    //  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);
}

class Cupboard {
    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);
}

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

    static Table table = new Table();
    static Cupboard cupboard = new Cupboard();
}

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

進程已結束,退出代碼 0

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