• 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

Method Overriding confusion

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.)
 
stable boy
Posts: 425
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks ,
But what do you mean by "more specific"??
 
Thomas De Vos
stable boy
Posts: 425
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic