This week's giveaways are in the MongoDB and Jobs Discussion forums.
We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Ambiguous method overloading Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Ambiguous method overloading" Watch "Ambiguous method overloading" New topic
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
    
    1

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
    
    1

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);
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Ambiguous method overloading
 
Similar Threads
overridden method
Instance variable initiating
overloading question
Passing null as a method argument
super . super