• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance Question which method is called  RSS feed

 
Markus Schmider
Ranch Hand
Posts: 149
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

the following code is from Boyarsky, Selikoff: OCA Study Guide


It is from a selftest question
The expected output is
DeerReindeer, false

First the default constructor of the superclass Deer is called, the ReindeerConstruct,
the method hasHorns(). Since deer is of the type Deer, the hasHorns() method from Deer is called.

However when I run the program I get
DeerReindeer,true

What's wrong???
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your understanding of how it works is wrong.

First, Deer() is not a default constructor. It is a no-argument constructor but since you specify it explicitly, it is not "default".

Second, even though the variable is declared as Deer, the actual instance is a Reindeer. Since hasHorns is an instance method, then polymorphic behavior is exhibited and the actual type's method is invoked.
 
Markus Schmider
Ranch Hand
Posts: 149
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok two mistakes on my side.
First the type of the object (Reeindeer) determines which overriden method is run.

Secondly I have not correctly copied the code from the book. The hasHorns() method on Deer is declared private
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!