jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes Object Vs String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Object Vs String" Watch "Object Vs String" New topic

Object Vs String

Prasath Thirumoorthy
Ranch Hand

Joined: Jul 23, 2004
Posts: 65
class Example {
public void myMethod(Object o) {
public void myMethod(String o) {

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

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

Joined: Jul 08, 2003
Posts: 24193

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.

[Jess in Action][AskingGoodQuestions]
Prasath Thirumoorthy
Ranch Hand

Joined: Jul 23, 2004
Posts: 65
Thanks a lot...
I agree. Here's the link: http://aspose.com/file-tools
subject: Object Vs String
It's not a secret anymore!