Typescript Foundations / Class & Object Oriented Typescript

Abstact classes and Methods

An abstract class:

  • Can define both concrete and abstract members

  • Cannot be instantiated directly

  • Is meant to be extended by other classes


✅ Syntax: Abstract Class

abstract class Animal {
  abstract makeSound(): void; // abstract method – must be implemented

  move(): void {
    console.log("The animal moves");
  }
}

❌ Error if you try this:

const a = new Animal(); // ❌ Error: Cannot create an instance of an abstract class

✅ Subclass Must Implement Abstract Methods

class Dog extends Animal {
  makeSound(): void {
    console.log("Woof!");
  }
}

const d = new Dog();
d.makeSound(); // "Woof!"
d.move();      // "The animal moves"

🔧 Abstract Methods

An abstract method:

  • Has no body in the abstract class

  • Must be implemented in the subclass

abstract class Shape {
  abstract getArea(): number;

  describe(): void {
    console.log("This is a shape.");
  }
}

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

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

🧠 Abstract vs Interface

Feature

abstract class

interface

Can have implementation

✅ Yes

❌ No

Can define fields & methods

✅ Yes

✅ Yes (method signatures only)

Multiple inheritance

❌ No

✅ Multiple interfaces possible

Use when

You need base class logic

You need only shape/contracts


🧪 Example: Payment System


🚀 Summary

Concept

Description

abstract class

Cannot be instantiated directly

abstract method

Must be implemented in subclass

Concrete methods

Can be included in abstract class

Purpose

Common structure + enforced methods