someMethod(null) is eligible to call someMethod(String str)& also someMethod(Byte byte). Since, it is eligible to call both methods, jvm is not able to decide which method it should call.
If Byte replaced by Object, works fine - why?
It is calling someMethod(String str)- why? sorry, no idea. [ November 23, 2004: Message edited by: sanjeevmehra mehra ]
In general it is ambiguous & should not be compiled.
I don't like guesswork, but as all knows Object is parent class (root), so that's making difference. I hope experts like Corey McGlone, Barry Gaunt, Jason Menard, Dirk Schreckmann can give better (actual) reason.
I also believe that it chooses the most specific. Between Object and String, String is more specific but Byte and String are at the same level of hierarchy.
When one someMethod() method accepts any Object, while the other someMethod() method requires a String, the "most specific" rule causes Java to choose the more specific method even if both methods could accept the particular argument.
Why gives compiler error saying reference to somemethod is ambiguous. Both somemethod match.
This is happening because the two somemethods' arguments are "Byte" and "String" respectively. Note that these two are peer classes. So the call using null becomes ambigous since both these peer classes are equally preferable and so, ambigous for complier to determine which one to call.
But
If Byte replaced by Object, works fine - why?
Now the case is different. The "String" extends "Object". So they share a Superclass-Subclass relationship. Now the compiler can stick on to the most specific call. i.e. null is more a String object compared to the Object. So there is no compile-time error since these are not peer classes. Thats it!!!
Remember: In such type of questions see the relationship - whether any is-a relation or peer classes.
Hello, Not sure but I think that the calling method passes "null" as a literal and hence the method which uses string in the argument list will be invoked rather than the method which uses object in its argument list.
Please do correct me if my understanding is wrong.
"" is the empty String. It is a literal of type String representing a String of zero characters.
null is a literal of type null. It can be assigned to a reference of any type, including String, but you get a NullPointerException if you try to use a reference variable equal to null to access an object or its members. It is not the empty String.
When choosing between same-named methods to invoke, Java will pick a method which can handle fewer cases over a method which can handle all of the first method's cases and some other cases besides. This is the "most specific" rule.
A method that can only handle an argument of type String or null will be chosen over another method that can handle an argument of any type.