0

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???

1
  • Your code won't compile. Both your show methods have the same erasure. Commented Apr 16, 2014 at 16:57

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.