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) {
}
No, you cannot overload a method based on different return type but same argument type and number in java.
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.
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.
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.
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).
Because then the compiler would be unable to figure out:
setVal(getVal());
should it call the bool or int version?
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