aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is this the appropriate at runtime ? 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 is this the appropriate at runtime ?" Watch "Why is this the appropriate at runtime ?" New topic
Author

Why is this the appropriate at runtime ?

Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Hello there!
You know when I thought I have seen everything there's to know about inheritance, comes a code that makes everything in my lil' Java domination world fall apart.. I'm talking about this:



The preceding code, outputs the following of course....

Dad:foo Son:foo Son:bar Son:bar

I agree 75% with the output given. because I don't get Why it outputs the First String, I mean:
Dad:foo

I thought that at runtime the method selected was always determined by the Object in Memory, not the reference variable..
So can anybody tell why exactly it is not as the theory states ?

Best Regards,
Jose !
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19073
    
  40

The bar() method is a good example of overriding a method.

The foo() method is an example of overloading a method. With overloading, it is actually dependant on the reference used to call the method. Using a Son reference, the foo() method that takes a single string does match better than the var-arg version. Using a Dad reference, only the var-arg version is available.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Tim Weide
Ranch Hand

Joined: Feb 19, 2008
Posts: 37
foo() isn't overridden (the signature is different), and since the reference is to a Dad, there is only one possibility: the foo() function, as defined in the Dad class.
Daniel Chemko
Ranch Hand

Joined: Feb 27, 2008
Posts: 32
You are seeing the magic of compile time vs. runtime processing. Apparently varg lists are enumerated and 'boxed' at compile time instead of performing it at runtime.

So once the compiler gets a hold of the class, the classfile pseudocode would look something like this:

Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Hello Guys!

My doubt has been cleared now. I feel like a fool now to be honest. I couldn't see it was an overload. and that was the end of the story. It's kinda pathetic because I've been studying for quite a long time now.

Thank you Henry ! you always pinpoint me to the root of the problem.
And thanks to you guys(the other posters) as well.

Be posting back soon!

Good Luck,
Jose
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why is this the appropriate at runtime ?