Shadowing & Hiding

What happens when a child and parent share the same variable name? Master Shadowing and Hiding to avoid subtle bugs.

April 20, 20262 min read14 / 14

When you start using inheritance, a strange thing can happen: both the parent and the child might have an attribute with the same name. This leads to two confusing behaviors: Shadowing and Hiding.

The Essentials

The "Variable Conflict" guide:

  1. Shadowing: When a local variable (inside a method) has the same name as a class attribute.
  2. Hiding: When a child class defines an attribute that already exists in the parent class.
  3. The "this" keyword: Use this.name to refer to the current class attribute, bypassing a local shadow.
  4. The "super" keyword: Use super.name to refer to the parent's attribute when the child is hiding it.

1. Shadowing (Local vs Class)

Shadowing happens within a single class. It's usually a mistake made during constructors.

class Student { name: string; constructor(name: string) { // name (parameter) shadows this.name (attribute) this.name = name; } }

2. Hiding (Child vs Parent)

Hiding happens across inheritance. If a parent has name and the child also defines name, the child "hides" the parent's version.

  1. The Conflict: Java sees two separate boxes labeled name in memory.
  2. The Choice: When you are inside the child class, the computer defaults to the child's box.
class Parent { name: string = "Parent"; } class Child extends Parent { name: string = "Child"; printNames() { console.log(this.name); // "Child" console.log(super.name); // "Parent" } }

Best Practice: Avoid Hiding

In professional LLD, we never define the same attribute name in a child class.

  1. It's Confusing: Other developers won't know which "name" they are touching.
  2. It's Unnecessary: The child already has the parent's name. If you need a different name, give it a different purpose (e.g., displayName).

By understanding how Java resolves these name conflicts, you can avoid the subtle bugs that happen when you accidentally "shadow" or "hide" the data you intended to change.

Congratulations! You've mastered the core pillars and patterns of Object-Oriented Programming. Next, we'll take these skills to the next level with the SOLID Principles.

Practice what you just read.

Quiz: Shadowing vs Hiding
1 exercise