aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hidden fields through inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hidden fields through inheritance" Watch "Hidden fields through inheritance" New topic
Author

Hidden fields through inheritance

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

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

Joined: Sep 20, 2010
Posts: 3649
    
  17

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

Joined: Jul 09, 2001
Posts: 1180
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

William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hidden fields through inheritance