Question 28:
What is the result of attempting to compile the following program:
public class Test{
public void method(StringBuffer sb){
System.out.println("StringBuffer Version");
}
public void method(
String s){
System.out.println("String Version");
}
public static void main(String args[]){
Test test=new Test();
test.method(null);
}
}
The answer is: Code does not compile, and compile error is reference to method is ambiguous.
However, in a piece of simliar code:
public class Test{
public void method(Object o){
System.out.println("Object Version");
}
public void method(String s){
System.out.println("String Version");
}
public static void main(String args[]){
Test test=new Test();
test.method(null);
}
}
This code works, and output is: String Version
I think for the first code, String & StringBuffer are two different string classes. "null" could be String or StringBuffer, so the compiler doesn't know which one it refer to. If we give a cast, then it should work. Am I right?
But for the second code, I really don't know why there is no compilation error, and why the output is String Version. I understand that Object is not a abstract class, so its instance could be null too. Anybody could tell me the trick here?