1. 先靜態對象,後非靜態對象,後建構函式。
2. 靜態成員初始化之後,再次初始化對象,靜態成員不會被第二次初始化。
public class Bowl { Bowl(int i){ System.out.println("Bowl"+i); } void Bowlf1(int i){ System.out.println("Bowl.f1--"+i); } }
public class Table { static Bowl bowl1=new Bowl(1); Table(){ System.out.println("Table()"); bowl2.Bowlf1(1); } void Tablef2(int i){ System.out.println("Table.f2--"+i); } static Bowl bowl2=new Bowl(2); }
public class Cupboard { Bowl bowl3=new Bowl(3);//後初始化 static Bowl bowl4=new Bowl(4);//先初始化靜態對象 Cupboard(){ System.out.println("Cupboard()"); bowl4.Bowlf1(2); } void Cupboardf3(int i){ System.out.println("Cupboard.f3--"+i); } static Bowl bowl5=new Bowl(5); }
public class StaticInitTest { public static void main(String[] args){ System.out.println("建立 Cupboard in main"); new Cupboard(); System.out.println("======================"); System.out.println("建立 Cupboard2 in main"); new Cupboard(); System.out.println("======================"); table.Tablef2(1); System.out.println("======================"); cupboard.Cupboardf3(1); } static Table table = new Table(); static Cupboard cupboard=new Cupboard(); }
輸出:
Bowl1
Bowl2
Table()
Bowl.f1--1
Bowl4
Bowl5
Bowl3
Cupboard()
Bowl.f1--2
建立 Cupboard in main
Bowl3
Cupboard()
Bowl.f1--2
======================
建立 Cupboard2 in main
Bowl3
Cupboard()
Bowl.f1--2
======================
Table.f2--1
======================
Cupboard.f3--1
說明:
以下兩句代碼在執行Main函數載入類的時候會先被初始化,
static Table table = new Table();static Cupboard cupboard=new Cupboard();
因為:當類被初始化為對象或者可能會訪問到類的靜態成員的時候都會引起類的載入。
如果我們不先初始化靜態成員的話,我們在下面用到的時候就會引發異常。
如果寫 Table table = new Table(); 那麼這一句則不會被執行,那麼這麼寫什麼時候會執行呢?
那就是StaticInitTest 被初始化的時候,
例如有一個Test類的main函數裡寫 StaticInitTest t= new StaticInitTest ();
那麼Table table = new Table();就會同時被初始化了!
看下面的例子:
public class Insect { private int i = 9; protected int j; public Insect() { System.out.println("i=" + i + ",j=" + j); j = 39; } private static int x1 = printInit("static Insect.x1 initialized"); static int printInit(String s){ System.out.println(s); return 47; } } public class Beetle extends Insect { private int k = printInit("Beetle.k initialized"); public Beetle() { System.out.println("k=" + k); System.out.println("j=" + j); } private static int x2 = printInit("static Beetle.x2 initialized"); static Insect insect=new Insect(); public static void main(String[] args) { System.out.println("Beetle constructor"); Beetle b = new Beetle(); } } 輸出: static Insect.x1 initialized static Beetle.x2 initialized i=9,j=0 Beetle constructor i=9,j=0 Beetle.k initialized k=47 j=39