Web Analytics

Abstract Classes

Intermediate~18 min

Abstract classes provide a blueprint for other classes, defining methods that must be implemented by derived classes.

TypeScript Abstract Classes

Abstract Classes

Output
Click Run to execute your code
Abstract Class Rules:
  • Cannot be instantiated directly
  • Can have abstract methods (no implementation)
  • Can have concrete methods (with implementation)
  • Child classes MUST implement abstract methods

Abstract vs Interface

Feature Abstract Class Interface
Can have implementation โœ“ Yes โœ— No
Can be instantiated โœ— No โœ— No
Multiple inheritance โœ— No โœ“ Yes
Constructor โœ“ Yes โœ— No
Use case Shared behavior + contract Pure contract

Common Mistakes

1. Trying to Instantiate Abstract Class

abstract class Shape {
    abstract getArea(): number;
}

let shape = new Shape();  // โœ— Error!

// โœ“ Create concrete child class
class Circle extends Shape {
    getArea() { return 0; }
}
let circle = new Circle();  // โœ“ OK

2. Not Implementing Abstract Methods

abstract class Animal {
    abstract makeSound(): void;
}

class Dog extends Animal {
    // โœ— Error - must implement makeSound()
}

// โœ“ Correct
class Dog extends Animal {
    makeSound() { console.log("Woof"); }
}
When to Use: Use abstract classes when you have shared implementation AND want to enforce a contract.

Summary

  • Abstract classes combine interfaces and base classes
  • Cannot instantiate abstract classes
  • Child classes must implement abstract methods
  • Can have both abstract and concrete members