I have the following methods:
void Method(string param1, string param2);
void Method(string param1, object param2);
When I call the method using the following:
method("string", null);
It gives me an error because the call is ambiguous, the compiler does not know which version to call, because both methods accept null
as the second parameter.
How do I overcome this without changing the method name in one of them? the first method will never have null
.
When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.
There are ambiguities while using variable arguments in Java. This happens because two methods can definitely be valid enough to be called by data values. Due to this, the compiler doesn't have the knowledge as to which method to call.
Overloading. Method overloading is a form of polymorphism in OOP. Polymorphism allows objects or methods to act in different ways, according to the means in which they are used. One such manner in which the methods behave according to their argument types and number of arguments is method overloading.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
The problem is that both string
and object
are nullable, so null
could refer to either overload of the method. You have to cast the null value—as stupid as that sounds—to say explicitely which overload you want to call.
method("string", (string) null);
method("string", (object) null);
This is basically the same as if you defined a variable of either type and passed that then:
string param1 = null;
object param2 = null;
method("string", param1); // will call the string overload
method("string", param2); // will call the object overload
Both param1
and param2
have the same value, null
, but the variables are of different types which is why the compiler is able to tell exactly which overload it needs to use. The solution above with the explicit cast is just the same; it annotates a type to the null
value which is then used to infer the correct overload—just without having to declare a variable.
You can be specific about which version of the method you want to call by specifying which type of null you're passing:
Method("string", null as string);
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