aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why does it behave like that? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why does it behave like that?" Watch "why does it behave like that?" New topic
Author

why does it behave like that?

Bogdan Sheptunov
Greenhorn

Joined: Aug 31, 2001
Posts: 5
Got a piece of code from one of the mock exams, which I can't explain. Who can tell me why it compiles, and prints "String Version"?
public class StringTest{
public void method(Object o) {
System.out.println("Object Version");
}
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
StringTest test = new StringTest();
test.method(null);
}
}
Thank you very much.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Bogdan
What happens in a method call is that the most specific method of the appropriate class is the one that is called. In very general terms in the code you posted this wou,d be the String argument method because it is lower in the heirarchy than the Object argument method.
Here is the actual quote form the JLS section 15.12.2.2

If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

Basically, becasue you can pass a String as an argument to a method that is looking for an Object, the String method is the most specific.

Hope that clears it up for you

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
[This message has been edited by Thomas Paul (edited August 31, 2001).]


Dave
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
We have had this discussion before:
http://www.javaranch.com/ubb/Forum24/HTML/011295.html
------------------
Tom - SCJP --- Co-Moderator of the Programmer Certification Forums


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Bogdan Sheptunov
Greenhorn

Joined: Aug 31, 2001
Posts: 5
Thank you, I see now.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why does it behave like that?