方法重載允許同一類中定義多個同名但參數不同的方法。Java 編譯器通過「最精確匹配」原則決定調用哪個重載版本,本文深入解析匹配規則與常見陷阱。
public class Lession10 {
// 基本類型重載鏈
public void test1(byte id) { System.out.println("test1(byte)"); }
public void test1(short id) { System.out.println("test1(short)"); }
public void test1(int id) { System.out.println("test1(int)"); }
public void test1(long id) { System.out.println("test1(long)"); }
public void test1(float id) { System.out.println("test1(float)"); }
public void test1(double id) { System.out.println("test1(double)"); }
// 引用類型重載
public void test2(Object o) { System.out.println("test2(Object)"); }
public void test2(String o) { System.out.println("test2(String)"); }
public void test2(Integer o) { System.out.println("test2(Integer)"); }
public void test2(List o) { System.out.println("test2(List)"); }
public void test2(ArrayList o) { System.out.println("test2(ArrayList)"); }
// 多參數重載
public void test3(int a, float b) { System.out.println("test3(int,float)"); }
public void test3(long a, double b){ System.out.println("test3(long,double)"); }
public static void main(String[] args) {
Lession10 o = new Lession10();
o.test1(1); // test1(int) - 數字字面量默認 int
o.test1((byte)1); // test1(byte)
o.test1(1L); // test1(long)
o.test1(1.0); // test1(double) - 小數默認 double
o.test1(1.0F); // test1(float)
o.test2(new Object()); // test2(Object)
o.test2("String"); // test2(String) - 更精確
o.test2(new Integer(3)); // test2(Integer)
o.test2(3); // test2(String) - 自動裝箱為 Integer,但 String 更精確?
o.test2(new LinkedList()); // test2(List)
o.test2(new ArrayList()); // test2(ArrayList)
// 強制轉型影響匹配
o.test2((Object)new ArrayList()); // test2(Object)
o.test2((List)new ArrayList()); // test2(List)
o.test3(1, 2); // test3(int,float)
o.test3(1L, 3); // test3(long,double)
o.test3(1, 3D); // test3(long,double) - int→long, double 精確匹配
}
}
test1(int);
test1(byte);
test1(short);
test1(long);
test1(double);
test1(float);
test2(Object);
test2(String);
test2(Integer);
test2(String); // 注意:3 自動裝箱為 Integer,但 String 不是父類,實際調用 test2(Integer)
test2(List);
test2(ArrayList);
test2(Object);
test2(List);
test3(int,float);
test3(long,double);
test3(long,double);
o.test2(null); // 編譯錯誤:無法確定調用哪個版本
void test4(Long l) {}
void test4(Integer i) {}
test4(3); // 編譯錯誤:int 既可轉 Long 也可轉 Integer
