2

I know that overloading is something which is decided at compile time but when i try to run below example its gives me result which i am not able to understand

package miscellaneous;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CollectionsOverloading {

public static String classify(Set<?> s) {
    return "Set";
}

public static String classify(List<?> s) {
    return "List";
}

public static String classify(Collection<?> s) {
    return "Collection";
}

public static void main (String args[]) {

    Collection<?>[] collections = { new HashSet<String>(), new ArrayList<String>(), new HashMap<String, String>().values()};

    for (Collection<?> coll : collections) {
        System.out.println(classify(coll));
    }
    }
}

When i run this code snippet every-time i get the output as "Collection" which means that the classify method with argument as Collection is called.

Please explain

Scientist
  • 1,458
  • 2
  • 15
  • 31

3 Answers3

5

Since the classify method you are calling is static, you are choosing which one to call at compile-time, and not at run-time.

At compile-time, the compiler sees that collections is an array of Collection, and therefore binds to the public static String classify(Collection<?> s) version of classify.

Edit: even if these methods were non-static, you would still find the Collection version being called, since overloaded methods are bonded using static binding at compile-time while overridden methods are bonded using dynamic binding at runtime.

Community
  • 1
  • 1
tucuxi
  • 17,561
  • 2
  • 43
  • 74
1

As you already said, the linking to overloaded Methods is made at compile time. As you iterate through a List of Collection the compiler only knows that the current element is an instance of Collection so it linkes to the classify(Collection) Method, which is then always called.

F. Lumnitz
  • 688
  • 4
  • 11
0

becaluse coll is the type of Collection ,so every time call classify(Collection s) methed.if you want call other methed,you need convert the type.Here is the code:

Collection<?>[] collections = { new HashSet<String>(),new ArrayList<String>(), new HashMap<String, String>().values() };
for (Collection<?> coll : collections) {
    if(coll instanceof Set<?>){
        System.out.println(classify((Set<?>)coll));
    }
    else if(coll instanceof List<?>) {
        System.out.println(classify((List<?>)coll));
    }
    else {
        System.out.println(classify((Collection<?>)coll));
    }
}
Pan
  • 97
  • 3