This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Object Vs String  RSS feed

 
Prasath Thirumoorthy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Example {
public void myMethod(Object o) {
System.out.println("Object");
}
public void myMethod(String o) {
System.out.println("String");
}
}

Class Test {
public static void main (String arg[]) {
Example eg = new Example();
eg.myMethod(null);
}
}

Hi Friends,
Consider the above program.The output of that program is String why not Object.If I add one more myMethod(StringBuffer sb) and StringBuffer as the parameter.Its giving compilation Error.ie Ambiguos Error.

Kindly help me in this.And Give me a Reason behind those Stuff.

Thanks & Regards,
Prasath Thirumoorthy
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a very frequently asked question!

When the compiler is choosing between different overloaded versions of a method, it first tries to select the "most specific" overload that matches. In this case "null" matches both String and Object, but String is more specific because it's a subclass of Object.

If you add a StringBuffer version, though, then null matches all three versions, and there is no single "most specific" version, because String and StringBuffer are both direct subclasses of Object. Therefore, the compiler can't choose, and it's an error.
 
Prasath Thirumoorthy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!