The Irreversibility of Overrides and Uncovering Hidden Fields

Once a method has been overridden in a subclass, that method's behavior is no longer directly available to the user of the subclass. See Item 3 in Example 1 for an example. Sure, the subclass can use super to invoke the overridden method, but that mechanism isn't available through a reference to the subclass. Overriding is irreversible.

Hiding is a different story. Java allows you to hide fields, nested classes, and static methods. Hiding static methods was discouraged in Example 2, Hiding Static Methods in Java, so let's use instance fields here.

The program (also on GitHub) below contains a simple hierarchy of three classes. Each contains an instance field s.

Output 1 clearly shows that the s in C hides the s in its superclasses. Outputs 2 and 3 show that to access the hidden fields in the superclasses, you simply cast the reference to the appropriate type.

This is a key difference between hiding and overriding. Overriding is forever. Hidden items can be uncovered. All it takes is a cast.

Dedication

My grandfather had a wonderful shop in his basement. To me, it was a place of mystery and fascination, and I would spend hours wandering through it, looking at all the tools and projects in various states of completion. Not being much of a wood worker, I've never had the need for such a shop (not to mention that I lack a basement), but recently it occurs to me that my gear, computers, and software are my shop. This site is for my late grandfather and everyone else who takes personal pride in carefully executed work.