Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose between two method of the same name in Java

I'm trying to access a method in a class I made, but since it is similar in name and in number of arguments my IDE says the method is ambiguous. Here's a mock-up of what the two methods look like:

methodName(X, Y, Z) methodName(A, Y, Z) 

I called on the method, and passed in the value null for the first argument for the purpose of my test. Unfortunately I cannot rename the methods, change the order of the arguments or modify the structure of the method in any way. Is there a way I can differentiate between these two methods?

like image 298
tamuren Avatar asked May 03 '12 20:05

tamuren


People also ask

Can you have 2 methods with the same name in Java?

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.

When two methods have same name it is called?

Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes. There's a rule for overloading.

Can two methods have the same name but different return type?

We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types.

Can we declare two methods with same name in class?

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.


1 Answers

Cast the first argument to the type of the first parameter of the method you want to call, for example:

methodName((A) null, y, z); 
like image 58
fivedigit Avatar answered Sep 17 '22 17:09

fivedigit