Java过载混乱 [英] Java overload confusion
问题描述
java无法调用任何重载方法,如下所示: -
java is not able to call any overload method as shown below :-
class LspTest{
public void add(int a, float b){
System.out.println("First add");
}
public void add(float a, int b){
System.out.println("second add");
}
public static void main(String [] a){
LspTest test = new LspTest();
test.add(1,1);
}
}
请解释我对此感到困惑。
Please explain i am confused in this.
推荐答案
在你的方法中,你有参数(int,float)
和(float,int)
但是在调用方法时,你传递的是 int
(1,1 )
值。 Java编译器可以在需要时自动将cast float类型转换为int。但在这种情况下编译器无法决定自动类型转换哪个int为float。因此它显示出歧义。
In your methods you are having parameters (int, float)
and (float, int)
but when calling the method you are passing both the int
(1,1)
values. The Java complier can auto type cast float to int whenever needed. But in this case compiler cannot decide auto type cast which int to float. Therefore it shows ambiguity.
您需要将其称为 test.add(1f,1);
或 test.add(1,1f);
即指定哪个值为int,哪个值为float。
You need to call it test.add(1f, 1);
or test.add(1,1f);
i.e. specify which value is int and which value is float.
PS要指定一个值为float,你可以用它写 f
。
P.S. To specify a value to be float you can write f
with it.
这篇关于Java过载混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!