Java调用重载方法
考虑这个代码段Java调用重载方法,java,methods,compiler-construction,Java,Methods,Compiler Construction,考虑这个代码段 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; }
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(byte,int)调用一个方法。因为int比long更具体,所以调用第一个方法。更具体地说,int是包含byte的两种类型中较小的一种
但是,编译器无法始终找出最具体的候选对象:
public static void foo(long a, double b) {
// body
}
public static void foo(double a, long b) {
// body
}
foo(3, 4);
这段代码不会编译,因为不清楚这些方法是什么意思。如果有重载的方法,编译器会使用方法签名找出最具体的候选方法。在这种情况下,两个签名是
buy(int, double)
及
请注意,返回类型不是签名的一部分。您正在使用buy(byte,int)调用一个方法。因为int比long更具体,所以调用第一个方法。更具体地说,int是包含byte的两种类型中较小的一种
但是,编译器无法始终找出最具体的候选对象:
public static void foo(long a, double b) {
// body
}
public static void foo(double a, long b) {
// body
}
foo(3, 4);
这段代码不会编译,因为不清楚这些方法是什么意思。也要通过也要通过