Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

method call in compile time or run time...

Status
Not open for further replies.

lovekang

Programmer
Feb 16, 2006
86
KR
This is from Effective java Item 26.

I'm not clear why the method does not call method1,2 in the for loop.

it says in method overloading the method is selected when compile time not run time.

help me out what is "the method is selected when compile time not run time."

thanks in advance.

import java.util.*;

public class Test {
public static String classify(Set s) { // method1
return "Set";
}

public static String classify(List l) { // method2
return "List";
}

public static String classify(Collection c) { //method3
if(c instanceof Set){
System.out.println("instanceof Set");
}
if(c instanceof List){
System.out.println("instanceof List");
}
return "Unknown Collection";
}

public static void main(String[] args) {
Collection[] tests = new Collection[] { new HashSet(), // A Set
new ArrayList(), // A List
new HashMap().values() // Neither Set nor List
};

for (int i = 0; i < tests.length; i++){
System.out.println(classify(tests));
}
System.out.println(classify(new HashSet()));
System.out.println(classify(new ArrayList()));
System.out.println(classify(new HashMap().values()));
}
}
 
Doesn't the book explain that? I think I'll blacklist it.

When you overload a method, the method called depends on the type of the argument.

In this case, when calling classify in the for loop, you're passing test, that's a Collection and the compiler inlines the classify method with a Collection argument because it has no way to know what's inside.

At runtime, you are actually passing a Set or List parameter. If the method were resolved a runtime, the proper classifu for Set or List would be called.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top