This week's book giveaway is in the General Computing forum.
We're giving away four copies of Learning Regular Expressions and have Ben Forta on-line!
See this thread for details.
Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Inheritance Question which method is called  RSS feed

 
Ranch Hand
Posts: 153
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???
 
Sheriff
Posts: 12355
201
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: 153
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!