In the following code snippet, there are three versions of a method named show()
.
package overloading;
import java.util.ArrayList;
import java.util.List;
public final class Main
{
private void show(Object object)
{
System.out.println("Object");
}
private void show(List<Object> list) //Unused method
{
System.out.println("List");
}
private void show(Object[] objects)
{
System.out.println("Objects");
}
private void addToList()
{
List<String>list=new ArrayList<String>();
list.add("String1");
list.add("String2");
list.add("String3");
show(list); // Invokes the first version
String []s={"111", "222", "333"};
show(s); // Invokes the last version
}
public static void main(String[] args)
{
new Main().addToList();
}
}
In this simplest of Java code, this method call show(s);
(the last line in the addToList()
method) invokes the last version of the overloaded methods. It supplies an array of strings - String[]
and it is accepted by the receiving parameter of type Object[]
.
This function call show(list);
however attempts to invoke the first version of the overloaded methods. It passes a list of type strings - List<String>
which should be accepted by the middle version whose receiving parameter is of type List<Object>
The middle version of the methods is completely unused. It is a compile-time error, if the first version is removed.
Why does this call show(list);
not invoke this version - private void show(List<Object> list){}
- the middle one?