考虑这个代码段
class StockServer {
StockServer(String company, int Shares,double currentPrice, double cashOnHand) {}
double buy(int numberOfShares, double pricePerShare) {
System.out.println("buy(int,double)");
return 3.0;
}
float buy(long numberOfShares, double pricePerShare) {
System.out.println("buy(long,double)");
return 3.0f;
}
}
如果我执行这行代码,
StockServer a = new StockServer("",2,2.0,2);
byte b=5;
a.buy(b,2);
结果将是:buy(int,double)
我想知道编译器如何决定执行哪个方法?
最佳答案
如果您有重载方法,编译器会使用方法签名找出最具体的候选者。在这种情况下,两个签名是
buy(int, double)
和
buy(long, double).
请注意,返回类型不是签名的一部分。您正在使用 buy(byte, int) 调用方法。由于 int 比 long 更具体,因此调用第一个方法。更具体地说,int 是包含字节的两种类型中较小的一个。
但是,编译器始终无法找出最具体的候选者:
public static void foo(long a, double b) {
// body
}
public static void foo(double a, long b) {
// body
}
foo(3, 4);
此代码将无法编译,因为不清楚其中的方法是什么意思。
关于Java调用重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18160445/