当我们将int参数传递给重载方法时会发生什么,其中float作为一个方法的参数而另一个方法具有双重参数 [英] What happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param
问题描述
在超载概念中,我有一个疑问,就是这样。
当我使用int值重载方法时,方法调用的是float参数方法而不是double参数方法。
In overloading concept, i am having one doubt, that is . when i comes to overload the method with int value the method call's the float parameter method rather the double parameter method.
void method1(float f){
System.out.println('float');
}
void method1(double f){
System.out.println('double');
}
方法调用:
method call:
method1(10);
输出:float
output: float
如本教程中的java教程所述 link
如果浮点字面值以字母F或f结尾,则浮点字面值为float类型;否则它的类型是double,它可以选择以字母D或d结尾。
As stated in the java tutorials in this link A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
对于上面的情况,方法调用应该调用double参数方法。但是它调用了float参数方法。
For the above case the method call should call the double parameter method. But it call's float parameter method.
如何在这个区域发生重载过程?
How the process of overloading taking place in this area?.
推荐答案
测试代码的变体,除了 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
变体
- Between a
short
and anint
, if you call the overloaded method with abyte
, theshort
variant will be chosen - Between an
int
and along
, if you call the overloaded method with abyte
orshort
, theint
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
的方法更具体,因为任何调用都是由一个采用<$ c的方法处理的$ c> 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.
这篇关于当我们将int参数传递给重载方法时会发生什么,其中float作为一个方法的参数而另一个方法具有双重参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!