File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings" Watch "Strings" New topic



Joined: Nov 30, 2000
Posts: 12
Why the below program gives o/p as String version & not
Object version
If I change Object to Integer or StringBuffer it gives compiler error reference to method is ambiguous.I can't understand why it
is so ?
public class Test
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[])
Test test=new Test();
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The real question is how does Java handle null? The method overloading is working just fine. If you change the Object method to Integer you will get the ambiguous error. I do not know the reason the method is being used with the null but if you want to see the method overloading work initilized some objects of the same types as your method then make them null.

Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
When deciding which overloaded method to call, the JVM will always try to pick the mathod with the most specific matching argument.
In your case as given, both String and Object match the call, so since String is a subtype (ie. more specific) of Object, then it's called.
When you change method(Object) to method(Integer), then both method(Integer) and method(String) match the call. However, since String and Integer aren't related, there's no clue for the JVM to decide which to call - hence the Ambiguous message.
asheesh talwar
Ranch Hand

Joined: Dec 10, 2000
Posts: 31
Thanx Rob
I agree. Here's the link:
subject: Strings
jQuery in Action, 3rd edition