File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why does it behave like that?" Watch "why does it behave like that?" New topic

why does it behave like that?

Bogdan Sheptunov

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();
Thank you very much.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
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

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

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

Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
We have had this discussion before:
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

Joined: Aug 31, 2001
Posts: 5
Thank you, I see now.
I agree. Here's the link:
subject: why does it behave like that?
It's not a secret anymore!