Krishantha Dinesh
Krishantha Dinesh

Reputation: 377

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

I know the following program will have a compile error as:

The method runThis(Integer) is ambiguous for the type Other

What I don't understand is the reason.

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". Also I don't know the reason. Can anyone 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");
}

Upvotes: 3

Views: 1416

Answers (2)

rgettman
rgettman

Reputation: 178263

When you pass in null, that can be converted to any reference type. Java will attempt to find the overloaded method with the most specific type.

In your first example, the possibilities are Object, Integer, and ArithmeticException. Integer and ArithmeticException are both more specific than Object, yet neither are more specific than the other, so it's ambiguous.

In your second example, the possibilities are Object, Exception, and ArithmeticException. Exception and ArithmeticException are both more specific than Object, but ArithmeticException is also more specific than Exception, so the ambiguity is resolved in favor of ArithmeticException.

Upvotes: 9

Elliott Frisch
Elliott Frisch

Reputation: 201447

The null could be any Object (including an Integer). Add a cast,

Change this

runThis(null);

to

runThis((Integer) null);

or

runThis((Object) null);

And eliminate the ambiguity.

Upvotes: 5

Related Questions