重載調用

Q. When ambiguity exists between method calls, how does compiler resolve it? Why String version of the method is called instead of the  Object version in the following example?
// Overloading.java
//*******************************
public class Overloading {
public void method(Object o) {
System.out.println("Object Version");
}
// String is an Object, but a specific Object
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
Overloading test = new Overloading();
// null is ambiguous to both methods
// The more specific one is called
test.method(null); // String Version
}
}
//*******************************
A:
The answer is in the comments of above code, just remember that when ambiguity exists between method calls, compiler resolves it by choosing the more specific ones. If it does not work, it will error out.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章