標籤:
class Base{ public static int a = 10; public int b = 20; static { System.out.println("Static Init Base " + a); //System.out.println("Null Init " + b); } public Base() { System.out.println("Init Base " + this.b); }}//一級子類和基類包含的內容一樣class SuperClass extends Base{ //靜態變數、靜態塊執行順序,按書寫先後順序 public static int a1 = getSuperStaticNumber(); public int b1 = getSuperInstanceNumber(); public SuperClass() { System.out.println("Init SuperClass" + this.b1); } static { System.out.println("Static Init SuperClass" + a1); } public static int getSuperStaticNumber() { System.out.println("Static member init"); return 100; } public int getSuperInstanceNumber() { System.out.println("Instance member init"); return 200; }}//二級子類為測試該代碼的驅動類 public class Sub extends SuperClass{ public static int a2 = getStaticNumber(); public int b2 = getInstanceNumber(); public Sub() { System.out.println("Init SubClass " + this.b2); } public static int getStaticNumber() { System.out.println("Static member init Sub"); return 1000; } public int getInstanceNumber() { System.out.println("Instance member init Sub"); return 2000; } static { System.out.println("Static Init " + a2); } // 程式入口,main public static void main(String args[]) { new Sub(); }}
Static Init Base 10
Static member init
Static Init SuperClass100
Static member init Sub
Static Init 1000
Init Base 20
Instance member init
Init SuperClass200
Instance member init Sub
Init SubClass 2000
靜態變數,靜態代碼塊,成員,構造(從父到子)
java 基礎之類載入順序