在 Java 里“参数如何匹配”通常指 方法调用时,实参(调用方)如何与形参(方法定义)匹配。可以从下面几个层面来理解。
方法名 + 参数类型 + 参数个数 + 参数顺序 共同决定匹配哪个方法。
void test(int a) {}
void test(String a) {}
void test(int a, String b) {}
调用时:
test(1); // 匹配 test(int)
test("abc"); // 匹配 test(String)
test(1, "abc"); // 匹配 test(int, String)
✅ 只看参数,不看返回值
int test(int a) {}
void test(int a) {} // ❌ 编译错误,方法重复
当没有完全匹配的参数类型时,Java 会尝试自动转换。
void test(long x) {}
test(10); // int → long,可以匹配
常见顺序:
byte → short → int → long → float → double
char → int
⚠️ 不会自动“向下转”
void test(int x) {}
test(10L); // ❌ long 不能自动转 int
class Animal {}
class Dog extends Animal {}
void test(Animal a) {}
test(new Dog()); // ✅ Dog 是 Animal,可以匹配
✅ 父类形参可以接收子类实参
void test(Integer i) {}
test(10); // int → Integer(自动装箱)
void test(int i) {}
Integer x = 10;
test(x); // Integer → int(自动拆箱)
⚠️ 但不会同时做多次转换
void test(Long l) {}
test(10); // ❌ int 不能直接装箱成 Long
void test(int... nums) {}
调用方式:
test();
test(1);
test(1, 2, 3);
⚠️ 优先级最低:
void test(int a) {}
void test(int... a) {}
test(1); // 优先匹配 test(int)
当有多个方法都“可能匹配”时,Java 按以下顺序选择:
void test(int a) {}
void test(Integer a) {}
test(1); // ✅ 匹配 test(int)
泛型在编译期会被擦除,不参与重载匹配:
void test(List<String> list) {}
void test(List<Integer> list) {} // ❌ 编译错误
| 情况 | 结果 |
|---|---|
| 参数类型不匹配 | 编译错误 |
| 返回值不同 | 不能区分重载 |
| long → int | ❌ |
| 子类 → 父类形参 | ✅ |
| 多个方法都匹配 | 编译错误 |
如果你指的是:
可以告诉我具体场景,我可以针对性讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。