Abstract Classes

1. Welcome and Icebreaker:

  • If you could design a blueprint for any kind of object, what would it be?

2. Outline the Session:

  • We’ll learn about abstract classes in TypeScript: what they are, how to use them, and why they’re useful.
  • Learning Outcomes: Understand how to define abstract classes and methods, and how to implement them in subclasses.
  • Let’s get abstract!

3. Concept Explanation:

  • Abstract Classes are classes that cannot be instantiated directly. They are meant to be extended by other classes.
  • Abstract classes can have both implemented methods and abstract methods (methods without a body).
  • Subclasses must implement all abstract methods.
  • Use the abstract keyword for both classes and methods.

4. Live Coding Demonstration:

abstract class Shape {
  abstract getArea(): number;
  describe() {
    console.log(`This shape has an area of ${this.getArea()}`);
  }
}

class Circle extends Shape {
  radius: number;
  constructor(radius: number) {
    super();
    this.radius = radius;
  }
  getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

const circle = new Circle(5);
circle.describe(); // This shape has an area of 78.53981633974483
// const shape = new Shape(); // Error: Cannot create an instance of an abstract class.

5. Tasks:

  • Short Exercise:
    1. Create an abstract class Animal with an abstract method makeSound() and a concrete method move() that prints a message.
    2. Create a subclass Cat that implements makeSound().
    3. Create an instance of Cat and call both methods.