萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java 繼承體系中類初始化順序完整解析 (含靜態/非靜態區塊、建構子鏈)

初始化順序鐵律 (12 步驟)

  1. 父類 static 欄位
  2. 父類 static {} 靜態區塊
  3. 子類 static 欄位
  4. 子類 static {} 靜態區塊
  5. 父類一般欄位
  6. 父類 {} 實例初始化區塊
  7. 父類建構子
  8. 子類一般欄位
  9. 子類 {} 實例初始化區塊
  10. 子類建構子

驗證程式碼


package nie.test.extend;

public class Test {
  public static void main(String[] args) {
    new Son("s");
  }
}

class Father {
  static protected String s = "father_static_property_string"; // 1
  protected String b = "father_normal_property_string";        // 5
  static {
    s = "o";                          // 2
    System.out.print("d");
    System.out.print(s);              // 輸出: do
  }
  {
    b = "r";                          // 6
    System.out.print("a");
    System.out.print(b);              // 輸出: ar
  }
  Father() {
    this("@");                        // 7: 呼叫 Father(String)
    System.out.print("1");            // 8
  }
  Father(String s) {
    System.out.print(s);              // 輸出: @
  }
}

class Son extends Father {
  public static String s = "son_static_property_string"; // 3
  public String b = "son_normal_property_string";        // 9
  static {
    s = "j";                          // 4
    System.out.print("t");
    System.out.print(s);              // 輸出: tj
  }
  {
    b = "3";                          // 10
    System.out.print("6");
    System.out.print(b);              // 輸出: 63
  }
  Son() {
    System.out.print(".");            // 11
  }
  Son(String s) {
    this();                           // 呼叫 Son()
    System.out.print("com");          // 12
  }
}

執行輸出結果

dotjar63.com

逐段對應:

  • do → 父 static 區塊
  • tj → 子 static 區塊
  • ar → 父實例區塊
  • @ → 父建構子(String)
  • 1 → 父建構子()
  • 63 → 子實例區塊
  • . → 子建構子()
  • com → 子建構子(String)

核心觀念釐清

  • 靜態初始化:類載入時一次性執行,父→子順序
  • 實例初始化:每 new 一次執行,父→子順序
  • 建構子鏈:this() 先於本體執行;super() 隱含於子建構子首行
  • static 欄位/區塊 不參與實例化順序,僅在類載入階段

若您的輸出與 dotjar63.com 完全一致,恭喜掌握 Java 初始化機制!

copyright © 萬盛學電腦網 all rights reserved