这个java题为什么是这个答案?

来源:百度知道 编辑:UC知道 时间:2024/06/14 11:22:40
class A
{
void method(float f)
{
System.out.println("float:"+f);
}
void method(double f)
{
System.out.println("double:"+f);
}
// void method(long f)
// {
// System.out.println("long:"+f);
// }

public static void main(String args[])
{
new A().method(8);
new A().method(1.2f);

}
}
结果:
float:8
float:1.2
如果去掉注释:则
long:8
float:1.2

我不明白,8没有标明f,为什么不是默认double
这个应该是方法的重载吧!没有子类的继承关系,谈不上覆盖。本题考查的应该是默认是调用哪种重载形式,我只是不明白,取消注释前为什么调用float类型的方法,取消注释后调用long的方法,而不是两个都调用double的。

因为注释的是个全局方法,它覆盖了class A中的method方法。
// void method(long f)
// {
// System.out.println("long:"+f);
// }
所以在调用new A().method(8); 时,调用的实际是全局方法。