英文:
why i am not getting reference to method is ambiguous in the following code?
问题
我有一个基类或父类,其中有方法method1(int, int)和method1(double, double)进行了重载。
public class Sub extends Base {
@Override
method1(double, double) { `一些操作` }
main{
method1(1, 1); // 我没有得到编译错误(对方法的引用不明确)!在Java中
}
}
但在这种情况下是怎样的?
public class Test3 {
public static void JavaHungry(Exception e) {}
public static void JavaHungry(ArithmeticException e) {}
public static void JavaHungry(String s) {}
public static void main(String[] args) {
JavaHungry(null); // 对方法的引用不明确
}
}
英文:
I have base or parent class which has method1(int ,int) and method1(double,double) overloaded
public class Sub extends Base{
@overridden
method1(double,double) {`some manipulation`}
main{
method1(1,1); //i am not getting Compile Error(reference to method is ambiguous)!in java
}
}
like so but what is the case here?
public class Test3{
public static void JavaHungry(Exception e) {}
public static void JavaHungry(ArithmeticException e) {}
public static void JavaHungry(String s) {}
public static void main(String[] args) {
JavaHungry(null); // reference to method is ambiguous
}
}
答案1
得分: 0
在Java中,int
用1
表示,而double
用1.0
表示。
因此,当你调用method1(1, 1)
时,它会调用带有int参数的方法。
对于Java编译器来说,这不是模糊的。
简而言之,以下是当你传递这些类型的值时会发生的调用。
method1(1, 1)
--> int, int
method1(1.0, 1)
--> double, double(编译器会自动将1转换为double)
method1(1.0, 1.0)
--> double, double
英文:
In Java, int
is represented by 1
and double
is represented by 1.0
.
Hence when you invoke method1(1, 1)
it is invoking the method with int arguments.
For Java compiler, this is not ambiguous.
In short, following are the invocations that will happen when you pass these types of values.
method1(1, 1)
--> int, int
method1(1.0, 1)
--> double, double (compiler with auto cast the 1 to double)
method1(1.0, 1.0)
--> double, double
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论