• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

(Solved!) Inheritance, polymorphism and overriding.

 
Jem Hobstad
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, hello.

I've just been taking the Whizlabs free mock exam. There's one snippet I can't explain ...



I supposed it would output:
Super
Base
Derived

Well actually it does not...
At compile time b1 is known as a SuperBase, but the instance method that is called at runtime is a Base instance... so... why does it output SuperBase?

That being said, I don't understand why the third line is "Base". Same problem I suppose.

Any help welcome ... thanks
[ October 24, 2007: Message edited by: Jem Hobstad ]
 
Saurabh Verma
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jem,

I am not quite sure abut the reason,but as far as I concerned,here print method is overloaded not overriden because they have different argument list.As the method are overloaded,when you calling through the reference of super class,no hidding of methods occurs and they invoking the methods of super class.When invoking methods,references of SuperBase class is used.
That's why the out put is:

Super
Super
Base
[ October 24, 2007: Message edited by: Saurabh Verma ]
 
Jem Hobstad
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah that makes sense!
You're right, it's about overloading - my mistake.

Checking the S&B book:
"Reference type determines which overlaoded method will be used at compile time".
-> at compile time, the only known print method is the one from SuperBase. Even if the real object that is referenced by b1 has a more accurate overlaoded method, it's the one visible at compile time that is used.

Thanks Saurabh!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic