Access Modifiers in Abstract Classes
You'll learn: How protected members in abstract classes enable the Template Method pattern by exposing extension points (hooks) to subclasses only, not to external code.
The Protected Hook Pattern
Abstract classes often define a template — a high-level algorithm — while leaving specific steps for subclasses to fill in. The protected modifier is perfect for this: it lets your abstract class expose methods or properties that subclasses can override or use, without making them part of the public API.
Think of it like a restaurant chain with a standardized recipe (the template). The corporate chef defines the cooking steps (public cook()), but leaves certain flavor adjustments (protected addSeasoning()) that only franchisees (subclasses) can customize. Regular customers (external code) never see or touch those internal steps.
How It Works
In your abstract class, mark methods as protected when they're meant as extension points for subclasses. The abstract class can call these methods internally (in public methods), and subclasses can override them, but outside code cannot access them.
abstract class DataProcessor {
// Public template method - the main algorithm
public process(data: string): string {
const validated = this.validate(data);
const transformed = this.transform(validated);
return this.format(transformed);
}
// Protected hooks for subclasses to customize
protected abstract validate(data: string): string;
protected abstract transform(data: string): string;
// Protected with default implementation
protected format(data: string): string {
return data.trim();
}
}
class CSVProcessor extends DataProcessor {
protected validate(data: string): string {
if (!data.includes(',')) throw new Error('Invalid CSV');
return data;
}
protected transform(data: string): string {
return data.split(',').join('|');
}
// Can override or use default format
}
const processor = new CSVProcessor();
processor.process('a,b,c'); // Works: public method
// processor.validate('test'); // Error: protected, not accessible
Why This Matters
protected creates a contract for extension without polluting your public interface. External users call process() and don't need to know about validate() or transform(). Only people writing new processors need to see those hooks.
Key Takeaway: Use protected in abstract classes to expose customization points to subclasses only — this is the foundation of the Template Method pattern, keeping public APIs clean while enabling controlled extension.