The result of running the main is:
"Collection<?>".
Why is it not calling the method with ArrayList<Integer>
parameter?
import java.util.*;
public final class GenericClass<T> {
private void overloadedMethod(Collection<?> o) {
System.out.println("Collection<?>");
}
private void overloadedMethod(List<Number> o) {
System.out.println("List<Number>");
}
private void overloadedMethod(ArrayList<Integer> o) {
System.out.println("ArrayList<Integer>");
}
public void method(List<T> l) {
overloadedMethod(l);
}
public static void main(String[] args) {
GenericClass<Integer> test = new GenericClass<Integer>();
ArrayList l = new ArrayList<Integer>();
test.method(l);
}
}
Since l
is a List
, the only matching function is the first one. Overload resolution is done at compile time, not run time. The value of l
isn't taken into account, only its type.
As far as the language is concerned, this might as well be:
List l = foo();
test.method(1);
It doesn't care what value l
has.
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