• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused!!!!

 
darshan karle
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi everybody,

I came across a program and it is compiling and running fine.
public class AQuestion
{
public void method(Object o)
{
System.out.println("Object Verion");
}

public void method(String s)
{
System.out.println("String Version");
}

public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}

}
i dont know why it is printing String arg method statement not Object method Stmt.can anybody please explain

regards
darshan
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a common question that comes up very often here at the ranch. You can search for previous topics using "most specific method" or even via "AQuestion" (the name of the questions class).

Henry
 
Ben Zaidi
Ranch Hand
Posts: 151
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Darshan,

When an object is instantiated, and when it invokes a method, it will
call the method having a more specific and nearer associated version.
Object class lies in the top hierarchy and is more Generic class, while
String version lies more close in hierarchy, so string version method
is called.

Hope it helps.

Ben
 
Krishnamoorthy Vuyala Muralidharan
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Darshan

What Ben wrote is correct! You will understand a most important thing if you change your code as follows(which will ultimately does not compile because of the ambiguity):

public class AQuestion {
public void method(Integer o) {
System.out.println("Integer Verion");
}

public void method(String s) {
System.out.println("String Version");
}

public static void main(String args[]) {
AQuestion question = new AQuestion();
question.method(null);
}

}


The compile-time error is as follows:

The method method(Integer) is ambiguous for the type AQuestion

This makes you clear that the Integer and String has no relation at all! Both are from different hierarchies so for the compiler its not clear which method to invoke! But when you look at your example, it has two methods with the same name but different arguments method(Object o) and method(String s), for the compiler its clear that the String is a subclass of Object (as every class in Java is a subclass of Object) and for this reason the compiler invokes the more-specific version than the more generic version. I repeat, in the modified code above, the ambiguity is so clear and hence the compile-time error.

HTH.

Best regards
Kris
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic