Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading not working with different parameters [duplicate]

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;
}
like image 742
user1236048 Avatar asked Apr 04 '13 08:04

user1236048


People also ask

Can method overloading have different parameters?

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.

Can you overload two methods with the same number of 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).

What are two methods with the same name but with different parameters?

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.

Can method overloading be done in different classes?

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 .


2 Answers

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 just Map.

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.

like image 191
Duncan Jones Avatar answered Sep 28 '22 14:09

Duncan Jones


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.

like image 21
Sachin Gorade Avatar answered Sep 28 '22 14:09

Sachin Gorade