1. 程式人生 > >4.4.2 構建器初始化

4.4.2 構建器初始化

以及 過程 繼承 默認 模塊 對象 永遠 發生 tin

字段先初始化,之後才是構造方法;

字段又有static字段先初始化,之後非static初始化(int i;這個就初始化默認值)

技術分享圖片

class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Table {
static Bowl b1 = new Bowl(1);
Table() {
System.out.println("Table()");
b2.f(1);
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);
}
class Cupboard {
Bowl b3 = new Bowl(3);
113
static Bowl b4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
b4.f(2);
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);
}
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();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupboard t3 = new Cupboard();
} ///:~
Bowl 允許我們檢查一個類的創建過程,而Table 和 Cupboard 能創建散布於類定義中的Bowl 的 static 成
員。註意在 static 定義之前,Cupboard 先創建了一個非static 的 Bowl b3。它的輸出結果如下:
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)
static 初始化只有在必要的時候才會進行。如果不創建一個 Table 對象,而且永遠都不引用Table.b1 或
Table.b2,那麽 static Bowl b1 和b2 永遠都不會創建。然而,只有在創建了第一個 Table 對象之後(或者
發生了第一次static 訪問),它們才會創建。在那以後,static 對象不會重新初始化。
114
初始化的順序是首先static(如果它們尚未由前一次對象創建過程初始化),接著是非static 對象。大家
可從輸出結果中找到相應的證據。
在這裏有必要總結一下對象的創建過程。請考慮一個名為 Dog 的類:
(1) 類型為 Dog 的一個對象首次創建時,或者 Dog 類的static 方法/static 字段首次訪問時,Java 解釋器
必須找到Dog.class(在事先設好的類路徑裏搜索)。
(2) 找到Dog.class 後(它會創建一個 Class 對象,這將在後面學到),它的所有 static 初始化模塊都會運
行。因此,static 初始化僅發生一次——在 Class 對象首次載入的時候。
(3) 創建一個new Dog()時,Dog 對象的構建進程首先會在內存堆(Heap)裏為一個 Dog 對象分配足夠多的存
儲空間。
(4) 這種存儲空間會清為零,將Dog 中的所有基本類型設為它們的默認值(零用於數字,以及 boolean 和
char 的等價設定)。
(5) 進行字段定義時發生的所有初始化都會執行。
(6) 執行構建器。正如第6 章將要講到的那樣,這實際可能要求進行相當多的操作,特別是在涉及繼承的時

4.4.2 構建器初始化