Java Variable Hiding: How Subclass Fields Mask Base Class Members
The note explains Java's variable hiding where a subclass field with the same name as a superclass field conceals the original, demonstrates it with a Father‑Son example, shows the output, and warns that such practice can hurt code readability.
In Java, if a subclass declares a member variable with the same name as one in its superclass, the subclass variable hides the superclass variable—even when their data types differ; the hidden variable can only be accessed via the super keyword.
Example code illustrates this concept:
class Father{</code>
<code> public Strings = "父类";</code>
<code>}</code>
<code>class Son extends Father{</code>
<code> public String s = "子类";</code>
<code>}</code>
<code>public class SonTest{</code>
<code> public static void main(String[] args){</code>
<code> Son son = new Son();</code>
<code> System.out.println(son.s);</code>
<code> }</code>
<code>}Running the program prints 子类, confirming that the Son class's s field hides the field with the same name in Father.
The author notes that, although the language permits such hiding, it is generally discouraged because it can make the code harder to read and maintain.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
