为什么我在下面的代码中没有得到方法引用模糊的引用?

huangapple go评论135阅读模式
英文:

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中,int1表示,而double1.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

huangapple
  • 本文由 发表于 2020年5月4日 14:10:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/61586118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定