Reputation: 25
I have been asked this question in an interview.
can anyone explain it.
public class A{
public void show(List <String>list1,List<Integer>lists2){...}
public void show(List <Integer>list1,List<String>lists2){...}
}
public class B{
public static void main(..){
A a=new A();
List<String> list1;
List<Integer>lists2;
a.show(list1,lists2);
}
}
I said 2 function would be called.. but when i worte in neatbeans it gave error of same name function been called...??? why so isnt overloading concept used here???
Upvotes: 0
Views: 108
Reputation: 720
First, remove "public" from one of your class declaration (actually from class A) .
Second, the compiler is reading the parameter as show(list, list)
, so it is giving you the same method and there is no overloading occurring here.
As both parameters are show(list, list)
.
Remember, generics are used to distinguish the object type not the return type.
Hope it works.
Upvotes: 0
Reputation: 607
Java Generics are enforced at compile time, but the type of the Collection is erased, and what you're left with is a duplicate method. In an IDE, you would get some message about "same type erasure."
Here's a good discussion about it that I enjoyed:
http://mindprod.com/jgloss/generics.html
Upvotes: 1
Reputation: 85799
Due to type erasure, the arguments of the method will become List
.
public void show(List list1, List list2);
public void show(List list1, List list2);
Thus becoming invalid code.
Upvotes: 6