This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
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: 3615
    
  14

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: 1176
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