【发布时间】:2014-12-16 07:22:43
【问题描述】:
我有方法重载,例如:
public int sum1(int a, int b)
{
int c= a+b;
System.out.println("The method1");
return c;
}
public float sum1(int a, float b)
{
float c= a+b;
System.out.println("The method2");
return c;
}
public double sum1(float a, float b)
{
double c= (double) a+b;
System.out.println("The method3");
return c;
}
从main方法,假设我们有
double x=10.10f;
double y=10.20f;
x 和 y 的表观类型是 double,但实际类型是 float。当我打电话时
System.out.println(" the output is :"+cc.sum1(x,y));
编译时的错误。
The method sum1(int, int) in the type Class is not applicable for the arguments double, double).
通过将 double 转换为 float,它应该转到 sum1(即方法 3)的位置
【问题讨论】:
-
我什至没有看到任何
?。 -
“x 和 y 的表观类型是 double,但实际类型是 float” – 不,类型只是
double。原始类型不是多态的。float不是double的子类,即使它是:重载决议对 static 类型进行操作。此外,您的第二次超载是多余的。只需让编译器在调用时将int隐式转换为float。 -
@5gon12eder:
int到float是无损转换吗? -
@Thilo 是的。但是,
long到float不是。 -
看来他们只是简单地将其定义为无损/扩展。 § 5.1.2 JLS: “从
int到float,或从long到float,或从long到double的扩大原语转换,可能会导致精度损失——即,结果可能会丢失一些值的最低有效位。在这种情况下,生成的浮点值将是整数值的正确舍入版本,使用 IEEE 754 舍入到最近模式。”
标签: java casting overloading