Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method is ambiguous

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);
like image 214
Dhruv Raval Avatar asked Feb 10 '23 13:02

Dhruv Raval


1 Answers

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.

like image 142
TobiasR. Avatar answered Feb 13 '23 02:02

TobiasR.