首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 子類構造方法調用 super() 與其他方法的語法規則

     編輯:程式設計疑難解答

核心結論

子類構造方法可以同時調用 super(...) 和其他方法,但有嚴格語法限制:

  • super(...) 必須放在構造方法第一行。
  • 其他方法調用(包括 this(...)、普通方法)必須在 super(...) 之後。
  • 若不顯式寫 super(...),編譯器默認插入 super()(無參構造),仍佔第一行位置。

代碼示例

class Father {
    Father(String msg) { System.out.println("Father: " + msg); }
    void fatherMethod() { System.out.println("Father method"); }
}

class Son extends Father {
    Son(String msg) {
        super(msg);           // 必須第一行
        fatherMethod();       // 允許:調用父類普通方法
        this.sonMethod();     // 允許:調用自身方法
        System.out.println("Son constructed");
    }
    void sonMethod() { System.out.println("Son method"); }
}

常見編譯錯誤

// 錯誤 1:super 不在第一行
Son() {
    System.out.println("before super");
    super("msg");  // Compile error: call to super must be first statement
}

// 錯誤 2:this() 與 super() 不能共存
Son() {
    this("default");  // 若寫 this(),則不能再寫 super(),二者互斥
    super("msg");
}

設計建議

  • 構造器中避免調用可被覆寫的方法(父類構造調用子類覆寫方法時,子類字段尚未初始化,易導致 NPE 或邏輯錯)。
  • 若需複用初始化邏輯,提取為 private 或 final 方法,或使用工廠模式/建造者模式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved