I have the following code :
public class Main {
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[])
{
Main question = new Main();
question.method(null);//1
}
}
why is the result is “String Version” ? and why there is a compiler error if the first method takes a StringBuffer object ?
Another case : if the first method takes a StringBuffer object and I write question.method("word");the result will be “String Version” . Why ? why there is no compiler error ?
The JAVA spec says that in cases like this, the most specific function will be called. Since String is a sub type of Object – the second method will be called.
If you change Object to StringBuffer – there is no specific method since StringBuffer is not a sub type of String and vice versa. In this case the compiler does not know which method to call – hence the error.