Can two Java methods have the same name with different return type? The return type of the methods are different and they are declared with the same method's name.
Is that allowed?
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.
A method cannot return more than one type. The signature of a method contains the return type or void if the method doesn't return anything.
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.
If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.
Only, if they accept different parameters. If there are no parameters, then you must have different names.
int doSomething(String s); String doSomething(int); // this is fine int doSomething(String s); String doSomething(String s); // this is not
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