Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hidden fields through inheritance

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code example:




And the output:




Why does `p.aMethod()` not print 6 when p.x prints 6?

Thanks
 
Stephan van Hulst
Bartender
Pie
Posts: 5553
53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean: "Why does p.aMethod() print 6 while p.x doesn't?

It's because Child's x hides Parent's x.

Child's aMethod() on the other hand overrides Parent's aMethod(). So at runtime Child's version is always called, regardless of the formal type of the variable holding the reference to the Child.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good Day,

Supporting Stephan's statement my beloved outstanding book - Java 2 by Bill Brogden says on page #151 -

Now consider the following code fragment in which a Chapter object is created but the reference is cast to a BookElement variable. The question is: Which method is executed, the one in the Chapter class or the one in the Bookelement class?




The answer is related to the fact the objects always know what type they are; just being cast to a BookElement reference does not change the object type. Because the Java Virtual Machine resolves method calls at runtime using the actual object, the Chapter version of addText is executed.



Regards,
Dan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic