更新时间:2022-03-17 23:15:12
测试代码的变体,除了 byte
literal以及 short
, int
和 long $ c $的各种组合的重载方法c>似乎暗示编译器选择最小扩展转换,如果有多个可用。
Testing a variant of your code, except with a byte
literal and overloaded methods with various combinations of short
, int
, and long
appears to imply that the compiler chooses the "least widening" conversion if more than one is available.
因此:
short
和 int
之间使用字节
,将选择短
变体 int
和 long
,如果用字节调用重载方法
或短
,将选择 int
变体short
and an int
, if you call the overloaded method with a byte
, the short
variant will be chosenint
and a long
, if you call the overloaded method with a byte
or short
, the int
variant will be chosen等等。
因此,因为 long
可以扩大到 float
或 double
,因为 float
转换是最小扩展,浮动$选择c $ c>重载。
Thus, because long
can be widened to either float
or double
, and because the float
conversion is the "least widening", the float
overload is chosen.
我认为这是因为选择最具体的重载编译器解决多个可能的重载的方式。从JLS,第15.12.2.5节:
I think this is because of the "choose the most specific overload" way that the compiler resolves multiple possible overloads. From the JLS, section 15.12.2.5:
非正式的直觉是,如果第一个方法处理任何调用,则一个方法比另一个方法更具体方法可以传递给另一个没有编译时错误的方法。
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.
所以,这样一个方法需要 float
比采用 double
的方法更具体,因为任何调用都是由一个采用 float 总是可以通过一个 double
的方法来处理,但不是相反。
So by this, a method that takes a float
is "more specific" than a method that takes a double
because any invocation handled by a method that takes a float
can always be handled by a method that takes a double
, but not the other way around.