protected: Inheritance-Accessible Members
What you'll learn: How protected creates a middle ground between private and public, allowing subclasses to access members while keeping them hidden from external code.
The Visibility Problem protected Solves
You've seen public (accessible everywhere) and private (accessible only within the class). But what if you want a property or method that's hidden from outside code but available to subclasses? That's exactly what protected does.
Think of protected like a family recipe. You don't share it with the public (private would lock it away entirely), but you do pass it down to your children and grandchildren so they can use and modify it in their own cooking.
Basic protected Syntax
class Animal {
protected sound: string;
constructor(sound: string) {
this.sound = sound;
}
protected makeNoise(): void {
console.log(this.sound);
}
}
class Dog extends Animal {
constructor() {
super("Woof!");
}
bark(): void {
// ✓ Can access protected members from parent
this.makeNoise();
console.log(this.sound.toUpperCase());
}
}
const dog = new Dog();
dog.bark(); // Works
// dog.sound; // Error: Property 'sound' is protected
// dog.makeNoise(); // Error: Method is protected
When to Use protected
Use protected when you're building class hierarchies and want subclasses to access internal details without exposing them to the rest of your application. It's perfect for:
- Base class utilities that subclasses need
- Shared state across an inheritance chain
- Template method patterns where subclasses override behavior
Key Takeaway: protected members are accessible within the class and all its subclasses, but hidden from external code—perfect for building extensible class hierarchies while maintaining encapsulation.