• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strings

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

------------------
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx Rob
 
Get out of my mind! Look! A tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic