Private Fields and Inheritance
What you'll learn: How private fields behave differently from public properties when subclasses extend a parent class.
The Core Rule: Private Means Private
Private fields (those starting with #) are not inherited by subclasses. This is fundamentally different from how public properties work. When a child class extends a parent class, it can access the parent's public properties and methods, but private fields remain completely inaccessible to the subclass—they're locked inside their declaring class.
How This Works
Think of private fields like a parent's locked diary. Even though you're part of the family (a subclass), you don't get the key. The parent class can read and write its own private fields, but child classes cannot see or access them at all.
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
class PremiumAccount extends BankAccount {
addBonus() {
// ❌ This fails! #balance is not inherited
// this.#balance += 100; // SyntaxError
// ✅ Must use public methods instead
this.deposit(100);
}
showDetails() {
// ❌ Can't access parent's private field
// return this.#balance; // SyntaxError
// ✅ Use the public method
return this.getBalance();
}
}
Subclasses can have their own private fields with the same name—they don't conflict because each is truly private to its class.
class ChildAccount extends BankAccount {
#balance = 50; // Different from parent's #balance
getChildBalance() {
return this.#balance; // Returns 50, not parent's balance
}
}
Key Takeaway: Private fields are not inherited—subclasses cannot access or see their parent's private fields and must use public methods to interact with them.