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);
The problem is that your compiler dont know which method to use if you call o.sum(5, 5);
he could use void sum(int i, long j) { }
where he takes the first 5 as int and the second 5 as long
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With