Java 方法多載解析在基本型別參數上遵循「優先精確匹配,否則自動提升」的原則。本文將透過完整程式碼示範 byte、short、int、long、float、double、char 在多載方法中的匹配行為,並解析常數值、縮小轉換的特殊規則。
當呼叫參數型別**小於**方法參數型別時,Java 自動進行**擴寬轉換**(不損失精度):
byte → short → int → long → float → double
char → int → long → float → double
public class PrimitiveOverloading {
static void prt(String s) { System.out.println(s); }
// 七組多載方法,分別接受不同基本型別
void f1(char x) { prt("f1(char)"); }
void f1(byte x) { prt("f1(byte)"); }
void f1(short x) { prt("f1(short)"); }
void f1(int x) { prt("f1(int)"); }
void f1(long x) { prt("f1(long)"); }
void f1(float x) { prt("f1(float)"); }
void f1(double x) { prt("f1(double)"); }
// ... f2 缺 char、f3 缺 char/byte、f4 缺 char/byte/short、以此類推
void testConstVal() { // 常數值 5
f1(5); f2(5); f3(5); f4(5); f5(5); f6(5); f7(5);
}
void testChar() { char x='x'; f1(x); f2(x); ... }
void testByte() { byte x=0; f1(x); f2(x); ... }
// ... testShort, testInt, testLong, testFloat, testDouble 同理
}
| 呼叫參數 | f1(完整多載) | f2(無char) | f3(無char,byte) | f4(無char,byte,short) | 說明 |
|---|---|---|---|---|---|
| 常數 5 | f1(int) | f2(int) | f3(int) | f4(int) | 整數常數預設為 int |
| char 變數 | f1(char) | f2(int) | f3(int) | f4(int) | char 無精確匹配時提升為 int |
| byte 變數 | f1(byte) | f2(short) | f3(short) | f4(int) | 逐級提升 |
| short 變數 | f1(short) | f2(short) | f3(int) | f4(int) | 逐級提升 |
| int 變數 | f1(int) | f2(int) | f3(int) | f4(int) | 精確匹配 |
| long 變數 | f1(long) | f2(long) | f3(long) | f4(long) | 精確匹配 |
| float 變數 | f1(float) | f2(float) | f3(float) | f4(float) | 精確匹配 |
| double 變數 | f1(double) | f2(double) | f3(double) | f4(double) | 精確匹配 |
當呼叫參數**大於**方法參數(如傳 double 給 int 參數),**不允許自動轉換**,必須明確強制轉型:
void testDouble() {
double x = 0;
f1(x); // 匹配 f1(double)
f2((float)x); // 強制轉 float
f3((long)x); // 強制轉 long
f4((int)x); // 強制轉 int
f5((short)x); // 強制轉 short
f6((byte)x); // 強制轉 byte
f7((char)x); // 強制轉 char
}
這稱為縮小轉換,可能導致精度遺失或數值截斷,因此編譯器強制程式設計師明確寫出 (type) 表示「我知曉風險並承擔後果」。
char 是無號 16 位整數,範圍 0~65535char 多載時,**提升為 int**(而非 short),因 short 有負數範圍,不足以涵蓋所有 char 值'x' 若在 switch 或賦值給 char 變數則視為 char,否則視為 intsetInt/setLong)或包裝類別(Integer/Long)消除歧義char),減少隱性提升驚喜5 是 int,若需 byte/short 請加強制轉型 (byte)5Java 基本型別多載解析遵循「精確匹配 > 擴寬轉換 > 錯誤」原則。char 提升為 int、整數常數為 int、縮小轉換需強制轉型,是三大易混淆點。理解這些規則,能避免「以為呼叫 A 版本實際跑了 B 版本」的難除錯問題。