• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings

 
Asheesh_talwar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
test.method(null);
}
}
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic