问题描述
考虑此代码段
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)
The results would be : buy(int,double)
我想知道编译器如何决定执行哪种方法?
I want to know how the compiler decide which method to execute?
推荐答案
如果您有重载的方法,则编译器会使用方法签名找出最具体的候选方法.在这种情况下,两个签名是
If you have overloaded methods, the compiler figures out the most specific candidate using the method signature. In this case the two signatures are
buy(int, double)
和
buy(long, double).
请注意,返回类型不是签名的一部分.您正在使用buy(byte,int)调用方法.由于int比long更具体,因此调用第一个方法.更具体的表示int是两种类型中较小的一个,以包含字节.
Note that the return type is not part of the signature. You are calling a method using buy(byte, int). Since int is more specific than long, the first method is called. More specific means that int is the smaller of the two type to contain byte.
但是,编译器无法始终找出最具体的候选对象:
However, the compiler cannot figure out the most specific candidate all the time:
public static void foo(long a, double b) {
// body
}
public static void foo(double a, long b) {
// body
}
foo(3, 4);
此代码将无法编译,因为不清楚使用哪种方法.
This code will not compile, because it is not clear which of the methods is meant.
这篇关于Java调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!