java靜態資料與非靜態資料的初始化
靜態資料
列印結果
當StaticInitialization執行的時候,首先會載入
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
當執行new Table()的時候,他就會執行static Bowl bowl1 = new Bowl(1);
就會呼叫BOwl的構造方法,
Bowl(intmarker){
System.out.println("BOwl"+marker);
},打印出BOwl1
然後繼續呼叫staticBowlbowl2 = newBowl(2);
打印出BOwl2,執行完Table類裡面的靜態方法後,由於是
以上這些是執行StaticInitialization裡面的靜態資料
static Table table = new Table();
接下來會執行static Cupboard cupboard = new Cupboard();
就會呼叫static Bowl bowl4 = new Bowl(4);
打印出BOwl4
在執行static Bowl bowl5 = new Bowl(5);
打印出BOwl5
然後在呼叫非靜態資料,Bowl bowl3 = new Bowl(3);
打印出BOwl3
其次才執行Cupboard
打印出Cupboard,fl2
當初始化完StaticInitialization的靜態資料後,才會執行他的main方法
打印出Createing new Cupbord() in main
Mian方法裡面有new Cupboard();
由於Cupboard裡面的靜態資料已經載入過了,已經放進了靜態資料的記憶體區域,重新new Cupboard的時候將不會再次載入,但由於Bowl bowl3 = new Bowl(3);是非靜態資料,將會再次被載入,所以打印出BOwl3,在往下執行,呼叫Cupboard的構造方法,打印出Cupboard 和f12
然後再執行StaticInitialization的
newCupboard();這兩行程式碼,
依次打印出Createing new Cupbord() in main
BOwl3
Cupboard
f12
靜態資料與非靜態資料
列印結果
由於ExplicitStatic沒有靜態資料和常量,那就直接執行Main方法
打印出Inside main()
接下來執行Cups.cup1.f(99);
將會載入Cups裡面的
就會打印出CUp1 Cup2
由於不是例項化(new),所以就沒有執行構造方法,打印出f99
---------------------------------------------------------------------------------------------------------------------------------
非靜態資料
列印結果
由於Mugs類裡面沒有靜態資料,所以將會直接執行Main方法
打印出Inside,執行new Mugs();接下來將會執行常量,
Mug mug1;
Mug mug2;
{
mug1 = new Mug(1);
mug2 = new Mug(2);
System.out.println("mug1 & mug2");
}
打印出Mug1Mug2mug1 & mug2
然後再執行構造方法,打印出Mugs(),再執行System.out.println("new Mugs()");
再執行new Mugs(1);再次依照new Mugs();一樣,執行下去