在同一個類別中,方法名稱相同、參數列表不同(參數個數、型別、順序任一不同),即構成方法多載。與返回值型別、修飾符、拋出異常無關。
public class MathUtils {
// 1. 參數個數不同
public int add(int a, int b) { return a + b; }
public int add(int a, int b, int c) { return a + b + c; }
// 2. 參數型別不同
public float add(float a, int b, int c, int d) { return a + b + c + d; }
public double add(double a, double b) { return a + b; }
// 3. 參數順序不同
public String concat(String prefix, int num) { return prefix + num; }
public String concat(int num, String suffix) { return num + suffix; }
}
// 錯誤:僅返回型別不同
public int compute(int a) { return a * 2; }
public double compute(int a) { return a * 2.0; } // Compile Error!
// 錯誤:參數名不同但型別順序相同
public void print(String msg, int times) { ... }
public void print(String text, int count) { ... } // 同一簽名,編譯錯誤
int → long → float → double、char → int、子類 → 父類。int ⇄ Integer。T... 優先級最低(最後嘗試)。注意:若多條路徑皆可行,編譯器報「模稜兩可」錯誤,需強制轉型消除歧義。
void f(int...) vs void f(Integer...))。@Nullable + 單一方法 + 內部判斷,或 Builder 模式。this(...) 串聯減少重複代碼。方法多載是靜態多態的基礎,核心在於「同名異參」。掌握解析優先級、避開陷阱,能讓 API 設計更直觀、易用。