Lesson 4 of 8
Abstract Classes
Abstract classes define a partial implementation that subclasses must complete. Unlike interfaces, abstract classes can contain implemented methods and state. Unlike concrete classes, they cannot be instantiated directly. They're the pattern for sharing behaviour across related types while enforcing a specific extension contract.
Abstract Classes - Shared Logic + Enforced Contract
// ── Abstract class - cannot be instantiated directly ─────────
abstract class BaseNotifier {
// Concrete method - all notifiers share this logic
async notify(userId: number, message: string): Promise<void> {
const user = await this.findUser(userId);
if (!user) throw new Error(`User ${userId} not found`);
const formatted = this.format(message, user);
await this.send(user, formatted); // abstract - subclass provides
this.log(`Notified ${user.name}`); // concrete shared logic
}
// Concrete shared helper
private log(msg: string): void {
console.log(`[${new Date().toISOString()}] ${msg}`);
}
private async findUser(id: number): Promise<User | null> {
// shared lookup - subclasses don't repeat this
return userRepo.findById(id);
}
// Abstract methods - MUST be implemented by subclasses
protected abstract format(message: string, user: User): string;
protected abstract send(user: User, message: string): Promise<void>;
}
// ── Concrete subclasses ───────────────────────────────────────
class EmailNotifier extends BaseNotifier {
constructor(private readonly mailer: MailService) {
super();
}
protected format(message: string, user: User): string {
return `Dear ${user.name},
${message}
Regards,
Task Manager`;
}
protected async send(user: User, message: string): Promise<void> {
await this.mailer.send({ to: user.email, subject: "Notification", body: message });
}
}
class SlackNotifier extends BaseNotifier {
constructor(private readonly webhookUrl: string) { super(); }
protected format(message: string, user: User): string {
return `*${user.name}*: ${message}`;
}
protected async send(_user: User, message: string): Promise<void> {
await fetch(this.webhookUrl, {
method: "POST",
body: JSON.stringify({ text: message }),
});
}
}
// ── Cannot instantiate abstract class ─────────────────────────
// new BaseNotifier(); // ❌ Error: Cannot create an instance of abstract class
const email = new EmailNotifier(mailer);
const slack = new SlackNotifier("https://hooks.slack.com/xxx");
// Both work because they share the notify() logic from the base:
await email.notify(1, "Your task was completed!");
await slack.notify(1, "Your task was completed!");
// ── Abstract class vs interface - when to choose ──────────────
// Interface: no shared state, no implementation, pure contract
// Abstract: shared implementation + enforce subclass contractCommon Mistakes
- Using abstract classes when interfaces are sufficient - if you don't need shared implementation, an interface is simpler and more flexible (a class can implement multiple interfaces but extend only one abstract class).
- Making everything abstract - only mark methods `abstract` that truly have no sensible default. Methods with a reasonable default implementation should be concrete (optionally overridable).
- Not calling `super()` in subclass constructor - if the abstract base class has constructor arguments or initialisation logic, subclasses MUST call `super()`. Forgetting this causes runtime errors.
Tip
Tip
Practice Abstract Classes in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Abstract Classes
Practice Task
Note
Practice Task - (1) Write a working example of Abstract Classes from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Abstract Classes is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Abstract classes define a partial implementation that subclasses must complete.
- Using abstract classes when interfaces are sufficient - if you don't need shared implementation, an interface is simpler and more flexible (a class can implement multiple interfaces but extend only one abstract class).
- Making everything abstract - only mark methods `abstract` that truly have no sensible default. Methods with a reasonable default implementation should be concrete (optionally overridable).
- Not calling `super()` in subclass constructor - if the abstract base class has constructor arguments or initialisation logic, subclasses MUST call `super()`. Forgetting this causes runtime errors.
Finished this lesson?