The method is ambiguous

2019-05-10 07:03发布

问题:

I am trying to understand method overloading and I'm not able to understand the reason for the following code error in the following example

public class OverLoading_OverRiding {
     public static void main(String[] args) {
        OverLoading_OverRiding o = new OverLoading_OverRiding();
        o.sum(5, 5);
    }

    void sum(int i, long j) {   }
    void sum(long i, int j) {   }
}

I am getting an error:

The method sum(int, long) is ambiguous for the type OverLoading_OverRiding.

When i am performing explicit casting on the same example then it works:

    o.sum(5, (long)5);

回答1:

The problem is that your compiler dont know which method to use if you call o.sum(5, 5);

  1. he could use void sum(int i, long j) { } where he takes the first 5 as int and the second 5 as long

  2. he could use void sum(long i, int j) { } where he takes the first 5 as long and the second 5 as int

since both methods would be valid to use in this example and your compiler always needs exactly one valid option, you get the error msg that your method is ambiguous.

if you call o.sum(5, (long)5); it matches only the method void sum(int i, long j) { }


The Question is, why would you overload a method this way? Mostly overloading is used for optional parameters like this:

void myMethod(int i) {}
void myMethod(int i, bool b) {}
void myMethod(int i, string s) {}

so you could call this method like:

myMethod(42);
myMethod(42, true);
myMethod(42, "myString");

Maybe this gives you an idea of method overloading.



回答2:

i can't able to proper understand ambiguous type error reason

Compiler says that it doesn't know which method to call. cause the call is ambiguous.



回答3:

Since 5 can be presented both as long and as an int the compiler cannot infer without more information to which of the two methods to call since their method signature is compatible for the same call.

When you cast the second argument to long the compiler can infer that the second signature can be used as there is no other option.

Also:

o.sum((int)5, 5); // or long

will work for the same reason



回答4:

Here is the reason,

Case 1: sum(int a, long b);

Here sum(5,5) matches this method.

How ? Since 1st parameter is int & calling method also int. Now next parameter is long but we are passing int. So what? its satisfy widening conversion/implicit type casting.

Example of implicit type casting:

int i=10;
double j;
j=i;
System.out.println(j);  // Output j=10.0

Same thing happens here, sum(5,5) matches => sum(int, long) & sum(long, int)

Case 2: sum(long a,int b)

sum(5.0, 5) matches both methods



回答5:

This is because 5 could be implicitly long or integer .. For this reason, method call is ambiguous.



回答6:

simple you hav to pass proper argument in your method that is in your first case o.sum(5, 5l) here first argument is int 5 and second is 5L for long and for your second case (5l, 5). this will work fine