No, Java does not allow method overloading based solely on different return types. For method overloading to be valid, the methods must have different parameter lists, such as a different number of parameters, different parameter types, or a different parameter order.
Key Points: • Method overloading is determined by the method signature, which includes the method name and parameter list. • The return type is not considered when resolving overloaded methods. • Two methods with the same name and parameters but different return types cause a compilation error. • The compiler would be unable to determine which method to call based only on the return type. • To overload a method, the parameter list must be different.
Example: The following code is invalid because both methods have the same signature and differ only in their return type.
Code Example:
class Calculator {
int calculate() {
return 100;
}double calculate() { // Compilation Error
return 100.0;
}
}Compilation Error:
method calculate() is already defined in class Calculator
Why Is It Not Allowed?
Consider:
calculate();
The compiler cannot determine whether it should call the int version or the double version because the method call is identical.
Valid Method Overloading:
class Calculator {
int calculate(int num) {
return num;
}
double calculate(double num) {
return num;
}
}Here, the parameter types are different, so overloading is valid.
Valid Overloading Examples:
• Different number of parameters
display(int a)
display(int a, int b)• Different parameter types
display(int a)
display(String a)• Different parameter order
display(int a, String b)
display(String b, int a)Invalid Overloading Example:
int display(int a)
double display(int a)
The above methods are invalid because only the return type differs.
Interview Tip: A concise interview answer is:
"No, methods cannot be overloaded solely by changing their return type. Java determines overloaded methods using the method name and parameter list, not the return type. To overload a method, the parameters must differ in number, type, or order."