This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I understand that the method chosen is the most specific one. However, my question is, when passed null, why is String argument more specific than the Object? [ April 10, 2005: Message edited by: M Rama ]
Joined: Mar 04, 2005
I found another problem along the same lines, which looks like this:
which does result in a compiler error, as expected.
I think the missing piece in this discussion is that a null reference can be converted to any type of object. Therefore, calling method(null) could potentially invoke either method(String s) or method(Object o).
In general, a method declaration is "more specific" than another if its respective arguments could be converted (via method invocation conversion) to those of the other method.
In this case, a String can be converted to Object, but an Object cannot be converted to String, so the method taking the String argument is more specific.
However, a String cannot be converted to a StringBuffer, nor can a StringBuffer can be converted to a String (since neither extends the other), so an error results.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org