Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this the appropriate at runtime ?

 
Jose Campana
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20894
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tim Weide
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic