File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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?

Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4627

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.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Dan Drillich
Ranch Hand

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


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:
subject: Hidden fields through inheritance
It's not a secret anymore!