Java編程思想筆記-類的初始化順序
阿新 • • 發佈:2017-07-07
rup cep main mark java boa marker 內存 類的初始化
1、如果有父類,先初始化父類,然後初始化子類
2、先初始化靜態成員變量、靜態代碼塊(static { }包圍的代碼),然後初始化非靜態成員變量、非靜態代碼塊(大括號包圍的代碼)。靜態成員變量間、非靜態成員變量間按定義順序初始化。
3、調用構造函數
class Bowl { Bowl(int marker) { System.out.println("Bowl(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } class Cupboard { Bowl b3 = new Bowl(3); 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); } 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); } public class Test { public static void main(String[] args) throws InterruptedException { 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(); }
1、開始運行,jvm先加載Test類,此時會初始化靜態成員變量 t2、t3
2、然後加載Table類,並初始化該類靜態成員變量b1、b2,調用Bowl構造 函數生成對象
3、調用Table構造函數,生成t2對象
4、加載Cupboard類,初始化靜態成員變量b4、b5,然後非靜態成員變量 b3,並調用Bowl構造函數
5、調用Cupboard構造函數,生成t3對象
6、運行main函數
7、運行 new Cupboard,此時Cupboard已加載入內存,靜態成員變量不會再初始化,但非靜態成員變量仍然再初始化一次
運行結果:
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)
Java編程思想筆記-類的初始化順序