Lesson 22 +10 XP

Abstract Classes & Abstract Methods

Abstract Classes & Abstract Methods

An abstract class serves as a base class that cannot be directly instantiated. It can contain both implemented methods and abstract method signatures.

Defining Abstract Classes

abstract class Shape {
  constructor(public color: string) {}

  // Abstract method: must be implemented by subclasses
  abstract getArea(): number;

  // Implemented method: shared across subclasses
  describe(): void {
    console.log(`Shape with color ${this.color}`);
  }
}

class Circle extends Shape {
  constructor(color: string, public radius: number) {
    super(color);
  }

  getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

// const s = new Shape("red"); // Error: Cannot create an instance of an abstract class.
const c = new Circle("blue", 5);
console.log(c.getArea()); // 78.5398...

TL;DR

  • Mark classes with abstract class ClassName to prevent direct instantiation.
  • Abstract methods have no body and MUST be implemented by derived subclasses.
  • Derived classes must call super() inside constructors.