• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confusion over overriding methods?  RSS feed

 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have written a piece of code which behaves in a way that goes against my understanding of inheritance in java.

I create a class having two methods, with one method calling other. Then I extend this class with another class
and override the two methods in parent class.



Output is:
B's methodX
A's methodY
B's methodY


I was expecting that call to methodX() in parent's methodY() would invoke parent's methodX() as when a child object is created then parent object is also created underneath.
And all super calls are basically called on this underlying parent object.
Where is my understanding wrong?

Manish
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
manish ghildiyal wrote:as when a child object is created then parent object is also created underneath


I think that's the source of your misunderstanding. There's only one object, which is of the child class and the parent class. That's why it can be misleading to refer to them as child/parent, because the relationship is completely different to a usual child/parent.

So polymorphism says that whenever you invoke a method on a particular object, you invoke the version belonging to the specific class of the object. That might be an inherited version, but not if it's been overridden. The only way to invoke the overridden implementation is with an explicit super.methodName() call. That's what you've done in methodY(), but you haven't done it in methodX().
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew.
Your answer has clarified the things.

Manish
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!