Junior — Middle
Is it possible to change the return type of a method when overloading it if the methods have the same parameter list?
sobes.tech AI
Answer from AI
In Java, you cannot change only the return type of a method when overloading it if the parameter list is the same. Overloading methods is based on differences in the method signature, which includes the method name and parameter types, but not the return type.
If two methods have the same name and the same parameter list but different return types, the compiler will produce an error because it cannot unambiguously determine which method to call.
An example that will cause an error:
class Example {
int method() { return 1; }
double method() { return 2.0; } // Compilation error
}
To change behavior, you need to modify the method parameters or use different method names.