Scientist
Scientist

Reputation: 1464

Collection overloading for different types of collections

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

Upvotes: 2

Views: 1315

Answers (3)

tucuxi
tucuxi

Reputation: 17955

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.

Upvotes: 5

Pan
Pan

Reputation: 97

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));
    }
}

Upvotes: 0

F. Lumnitz
F. Lumnitz

Reputation: 698

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.

Upvotes: 1

Related Questions