javajls

why i am not getting reference to method is ambiguous in the following code?


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
    }
}

Solution

  • 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