Error message "ambiguous for type" Other "when calling an overloaded method

I know the following program will have a compilation error like:

RunThis (Integer) method is ambiguous for type Other

I do not understand why.

public class Other {


    public static void main(String[] args) {

        runThis(null);

    }

    private static void runThis(Integer integer){
        System.out.println("Integer");
    }

    private static void runThis(Object object){
        System.out.println("Object");
    }

    private static void runThis(ArithmeticException ae){
        System.out.println("ArithmeticException");
    }

}

      

Also, when I change the program as follows, it prints "ArithmeticException". And I don't know the reason. Can someone explain this to me?

public class Other {


public static void main(String[] args) {

    runThis(null);

}

private static void runThis(Exception exception){
    System.out.println("Exception");
}

private static void runThis(Object object){
    System.out.println("Object");
}

private static void runThis(ArithmeticException ae){
    System.out.println("ArithmeticException");
}

      

+3


source to share


2 answers


On transition to null

, which can be converted to any reference type. Java will try to find the overloaded method with the most specific type.

In your first example, the possibilities Object

, Integer

and ArithmeticException

. Integer

and ArithmeticException

are more specific than Object

, but not more specific than others, so they are ambiguous.



In your second example, the possibilities Object

, Exception

and ArithmeticException

. Exception

and ArithmeticException

are more specific than Object

, but ArithmeticException

also more specific than Exception

, so ambiguity is allowed in favor ArithmeticException

.

+9


source


null

can be anything Object

(including Integer

). Add casting,

Change this

runThis(null);

      

to



runThis((Integer) null);

      

or

runThis((Object) null);

      

And remove the ambiguity.

+5


source







All Articles