作者eala (bucket list)
看板java
標題[問題] 關於物件初始化順序 static與 non-static
時間Thu Nov 3 15:22:35 2011
小弟最近在 K "Thinking in JAVA 4/e中文版"這本書
裡面第 157頁, 有個地方一直不太理解, 希望高手能幫忙解答
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);
Table(){
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int marker){
System.out.println("f2(" + marker + ")");
}
static Bowl bowl2=new Bowl(2);
Cupboard test=new Cupboard();
}
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("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
後面附了說明
"Bowl 讓你得以觀看 class的誕生過程, Table和 Cupboard會在它們自身的 class
定義式中產生 Bowl static 成員. 請記住, Cupboard會在 static定義之前先產生
non-static Bowl bowl3."
這段是什麼意思? 因為我怎麼試都試不出
Bowl(3)
Bowl(4)
Bowl(5)
的順序
先謝過~
感謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.114.71.19
→ lingerkptor:這是在教初始化的順序,建議你把code先拿去編譯並執行 11/03 16:25
→ lingerkptor:看印出的結果再來對照,再來了解那些部分先初始化。 11/03 16:27
→ lingerkptor:文義修正=> 之後 11/03 16:30
推 PsMonkey:利用版面資源,然後說相當歡迎站內信討論,這是什麼心態 11/03 16:35
→ eala:感謝回覆, 有跑出結果, 就是 Bowl(4) Bowl(5) Bowl(3)的順序 11/03 17:11
→ eala:主要附的說明看不懂, 程式結果感覺是 static優於 non-static 11/03 17:14
→ eala:版大不好意思~更正~ 11/03 17:17
※ 編輯: eala 來自: 140.114.71.19 (11/03 17:17)