| Author |
Ambiguous method overloading
|
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
Have look at the following code
the out put it is showing in String.
why not object. Bacause Object can also be null
Please Clarify regarding this.
Thanks And Regards
Anil Deshpande
|
Anil Deshpande
SCJP 1.5, SCWCD 1.5
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3785
|
|
According to the Java language specification:
If more than one member method is both accessible and applicable to a method invocation ... The Java programming language uses the rule that the most specific method is chosen.
Because String is a subclass of Object, the version with String is considered more specific.
Try adding the following method:
What do you think will happen now?
|
 |
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
it gives compile time error.
Some thing like ambiguous.
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3785
|
|
That's right. Because Integer and String are in different parts of the inheritance tree - neither is a parent of the other - the compiler doesn't consider one to be more specific than the other. So it doesn't know which version to call, and so you get the error.
But Object is a parent of String, so the String version is more specific than the Object version.
You can get round the ambiguity, if necessary, by using an explicit cast:
method1((Integer)null);
|
 |
 |
|
|
subject: Ambiguous method overloading
|
|
|