Why isn't this allowed and treated as same signature?
public Object myMethod(Map<String, String[]> values) {
return this;
}
public Object myMethod(Map<String, String> values) {
return this;
}
Method overloading in java is a feature that allows a class to have more than one method with the same name, but with different parameters.
No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
The practice of defining two or more methods within the same class that share the same name but have different parameters is called overloading methods.
Yes it is overloading , This overloading is happening in case of the class ' C ' which is extending P and hence having two methods with the same nam e but different parameters leading to overloading of method hello() in Class C .
The urban myth answer is:
Because type erasure causes the generics information to be lost. At runtime, those methods appear identical.
Map<X, Y>
becomes justMap
.
However, the actual answer appears to be more complex. See this excellent answer from a duplicate question. The compiler is actually quite capable of selecting the correct overloaded method given the supplied arguments, however the requirement to support legacy non-generics-aware code has forced the javac
developers to forbid it.
This is because of Type Erasure. Type Erasure removes most of the generics information at compile time. So above code after compilation would be
public Object myMethod(Map values) {
return this;
}
public Object myMethod(Map values) {
return this;
}
So both the methods are identical at runtime.
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