Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the less matching overloaded method is called

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);
}
}
like image 473
Yoda Avatar asked Feb 22 '23 03:02

Yoda


1 Answers

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.

like image 98
David Schwartz Avatar answered Mar 08 '23 10:03

David Schwartz