| Author |
Method Overriding confusion
|
Anand Sidharth
Ranch Hand
Joined: Dec 17, 2003
Posts: 44
|
|
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
Joined: Apr 12, 2003
Posts: 425
|
|
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 ]
|
Try your free <a href="http://www.javacertificate.com" target="_blank" rel="nofollow">SCJP 1.4</a> certification centre.<br />Try your free <a href="http://www.j2eecertificate.com" target="_blank" rel="nofollow">SCWCD</a> certification centre.<br />Try your free <a href="http://www.ejbcertificate.com" target="_blank" rel="nofollow">SCBCD</a> certification centre.<br />Try your <a href="http://www.webspherecertificate.com" target="_blank" rel="nofollow">Websphere (Test 285) </a> certification centre.<br />Try your <a href="http://www.j2mecertificate.com" target="_blank" rel="nofollow">SCMAD</a> certification centre. (New)<br /> <br /><a href="http://blogs.javacertificate.com" target="_blank" rel="nofollow">Java/J2EE Certification Blogging</a>
|
 |
Anand Sidharth
Ranch Hand
Joined: Dec 17, 2003
Posts: 44
|
|
Thanks , But what do you mean by "more specific"??
|
 |
Thomas De Vos
stable boy
Ranch Hand
Joined: Apr 12, 2003
Posts: 425
|
|
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.
|
 |
 |
|
|
subject: Method Overriding confusion
|
|
|