Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

so in java you can't have duplicate method names with different return and params?

Tags:

java

Is it possible to have two methods with the same name but different parameters and return types in Java? Seems like it would be a good way to generalize a simple getter and setter.. You can do that with constructors why not with regular methods ? for example

why not be able to do ..

int getVal() {

return int;
}

boolean getVal() {

return true;

}

setVal(int a) {
}

and

setVal(boolean a) {

}
like image 373
Ayrad Avatar asked Nov 04 '09 09:11

Ayrad


People also ask

Can we have same method with different return type in Java?

No, you cannot overload a method based on different return type but same argument type and number in java.

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 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.

Why is it possible to declare two methods with the same name?

Discussion. You can define two methods with the same name so long as they differ in the parameters they accept. One reasons for doing this is one function offers more customization (through parameterization) than the other function.


2 Answers

What would you expect if I called:

getVal();

with no return vaue being collected ? You have two choices - either the boolean or the integer variant. Since you can't enforce the return value to be collected, the compiler can't determine which variant to be called.

You can overload on method parameters, but not on the return types alone, since that's ambiguous (as shown above).

like image 188
Brian Agnew Avatar answered Nov 15 '22 10:11

Brian Agnew


Because then the compiler would be unable to figure out:

setVal(getVal());

should it call the bool or int version?

like image 44
Yngve Hammersland Avatar answered Nov 15 '22 09:11

Yngve Hammersland