Course contentsShow
← JavaScript
Lesson 795 of 2,72318. ClassesFree lesson

Private Fields and Inheritance

Understand that private fields are not inherited by subclasses and how this affects class hierarchies.

Private Fields and Inheritance

What you'll learn: You'll discover that private fields declared with # in a parent class are completely hidden from subclasses, which changes how you structure class hierarchies.

The Core Idea

When you declare a private field using the # syntax in a class, that field becomes truly private—so private that even classes that inherit from it cannot access it. Unlike regular properties or public fields, private fields don't travel down the inheritance chain. Each class's private fields are sealed off, visible only within that exact class.

Think of it like a locked personal diary. When a child inherits traits from a parent, they don't automatically get the key to the parent's diary. The parent's private thoughts stay private, even within the family.

How This Affects Your Code

class Parent {
  #secret = 'parent secret';
  
  getSecret() {
    return this.#secret; // Parent can access it
  }
}

class Child extends Parent {
  showSecret() {
    return this.#secret; // ❌ SyntaxError! Child cannot see Parent's #secret
  }
  
  tryParentMethod() {
    return this.getSecret(); // ✅ Works! Calls inherited public method
  }
}

The child class must use the parent's public methods (like getSecret()) to interact with private data. You cannot directly reference #secret from the child class—it simply doesn't exist in that scope.

Why It Matters

This design enforces true encapsulation. If you need subclasses to access certain data, use public or protected-style naming conventions (like _protectedField) instead of private fields. Private fields are for implementation details you never want anyone—not even your own subclasses—to touch.

Key Takeaway: Private fields with # are not inherited; subclasses cannot access or even reference a parent's private fields directly, only through the parent's public methods.