• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance question  RSS feed

 
Matt Road
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

someone can explain me why the voice method call for the parent class is not overrided from the child one ?
Indeed the code pint out "anima" instead of "donkey" that I'd expect
Thank you!




And second thing, why again I got "anima" print out in this second example ? Line7 should call the inherited method of voce ...

 
Ron McLeod
Saloon Keeper
Posts: 1600
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matt Road wrote:hello,
someone can explain me why the voice method call for the parent class is not overrided from the child one ?
Indeed the code pint out "anima" instead of "donkey" that I'd expect
Thank you!

In your example, Donkey is extending Animal, so the voice method in Donkey is overriding the voice method in its parent class - Animal.

In your main method, try instantiating a Donkey rather than an Animal.
 
Matt Road
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the thing is that the child method is not overriding the parent's one since I got the parent method running and not the child's one...
 
Ron McLeod
Saloon Keeper
Posts: 1600
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you extend a class, anything you do in the sub-class/child-class does not alter the super-class/parent-class. If you override a method in the sub-class, you will only see the different behaviour when you call the method in an instance of the sub-class, not the super-class.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matt Road wrote:the thing is that the child method is not overriding the parent's one since I got the parent method running and not the child's one...


Because you created a parent, not a child.

What if you were to create a Mongoose class that also extends Animal? Would you expect the voice method of both subclasses to be called when you create an Animal? Of course not.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!