Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overriding confusion

 
Anand Sidharth
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across the following example recently
public class A
{
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[])
{
A question = new A();
question.method(null);
}
}
In the above case I found that the output is
---"String Version".
I just need to know the why the method(String) is called.
(I thought there would a ambiguity error.)
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler will look to the most specific version. String is more specific then Object.
You can call the Object method if you want by casting the argument null.
method((Object)null) will use the method with the Object.
[ January 08, 2004: Message edited by: Thomas De Vos ]
[ January 08, 2004: Message edited by: Thomas De Vos ]
 
Anand Sidharth
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ,
But what do you mean by "more specific"??
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant with more specific that the String class inherits from the Object class. With other words the Object class is a superclass of String.

The compiler has to use some rules for choosing the correct method. This is done form bottom to up in the class hierarchy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic