Abstract classes help you create a base blueprint for other classes. They let you define common features while forcing specific parts to be made by child classes.
Abstract classes in Typescript
abstract class Animal { abstract makeSound(): void; move(): void { console.log('Moving around'); } } class Dog extends Animal { makeSound(): void { console.log('Bark'); } }
An abstract class cannot be instantiated directly.
Abstract methods have no body and must be implemented by subclasses.
startEngine must be defined in Car.abstract class Vehicle { abstract startEngine(): void; } class Car extends Vehicle { startEngine(): void { console.log('Car engine started'); } }
Shape forces area method. Circle provides its own calculation.abstract class Shape { abstract area(): number; } class Circle extends Shape { radius: number; constructor(radius: number) { super(); this.radius = radius; } area(): number { return Math.PI * this.radius * this.radius; } }
abstract class Employee { abstract getSalary(): number; } // Error: Cannot create instance of abstract class // const emp = new Employee();
This program shows an abstract class Animal with an abstract method makeSound. Two classes Dog and Cat implement this method. We create objects of Dog and Cat and call their methods.
abstract class Animal { abstract makeSound(): void; move(): void { console.log('Moving around'); } } class Dog extends Animal { makeSound(): void { console.log('Bark'); } } class Cat extends Animal { makeSound(): void { console.log('Meow'); } } const dog = new Dog(); dog.move(); dog.makeSound(); const cat = new Cat(); cat.move(); cat.makeSound();
Time complexity depends on the methods you implement, not on abstract classes themselves.
Abstract classes help organize code and enforce rules for subclasses.
Common mistake: Trying to create an instance of an abstract class directly causes an error.
Use abstract classes when you want to share code and force certain methods to be implemented. Use interfaces if you only want to enforce method signatures without code.
Abstract classes provide a base with some shared code and some methods to be defined by subclasses.
You cannot create objects from abstract classes directly.
They help organize related classes and enforce important methods.