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.
// 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.