这个问题可能类似于 Java overload confusion
我正在阅读一本书,其中有一个关于方法重载的主题,编译器可能无法从中解析被调用的方法。书中的例子使用了带有两个参数(int, double)
和(double, int)
的重载方法。调用此方法如 overloadedTwoParam(4, 5) 将导致编译器错误,因为 int 可以传递给 double。我的问题是,如果我的参数只有一个,为什么编译器能够解析将调用哪个方法?
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.overloadedSingleParam(1); //this is working
t.overloadedTwoParam(4, 5); //this is NOT working
}
void overloadedSingleParam(double a) {
// do something here..
}
void overloadedSingleParam(int a) {
// do something here..
}
void overloadedTwoParam(double a, int b) {
// do something here..
}
void overloadedTwoParam(int a, double b) {
// do something here..
}
}
最佳答案
My question here is why compiler able to resolve which method will be called if my parameter is only one
当涉及到单个参数时,编译器能够看到有一个采用int
的方法,因此不会混淆应该调用哪个方法。即使您删除采用单个 int
的方法,编译器仍将能够调用采用单个 double
的方法,因为这里没有歧义。 (int
可以提升为 double
)
当谈到交替使用 int
和 double
参数的其他方法时,编译器不想负责决定是否将第一个参数提升为double
或 double
的第二个参数。
关于java - 方法重载 : Single parameter vs alternating parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050143/