Vishrant
Vishrant

Reputation: 16638

Compile time error: ambiguous on calling overloaded method. Why?

For the code below, why do I get this compile time error:

The method overloadedMethod(IOException) is ambiguous for the type Test.

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
        test.overloadedMethod(null);

    }

    void overloadedMethod(IOException e) {
        System.out.println("1");
    }

    void overloadedMethod(FileNotFoundException e) {
        System.out.println("2");
    }

    void overloadedMethod(Exception e) {
        System.out.println("3");
    }

    void overloadedMethod(ArithmeticException e) {
        System.out.println("4");
    }

}

Upvotes: 2

Views: 591

Answers (2)

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Both FileNotFoundException and ArithmeticException are in the same level in java object hierarchy. Compiler confused to choose most specific method, Since both method are eligible for invocation.

Even Compiler can't choose most specific method, if there are multiple object hierarchies. So removing either of FileNotFoundException or ArithmeticException won't solve the problem.

From JLS 15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

Upvotes: 6

Nivas
Nivas

Reputation: 18334

You have four versions of overloadedMethod that accept parameters of type IOException, FileNotFoundException, Exception and ArithmeticException.

When you call

test.overloadedMethod(null);

the JVM cannot know which version of the method you are intending to call. That is why the ambiguous error.

You need to be more specific on which version you want to call. You can do that by casting the parameter:

test.overloadedMethod((IOException)null);

Upvotes: 1

Related Questions