Abstract methods let you define a method without a body in a base class. This means child classes must create their own version of this method. It helps make sure all child classes follow the same rules.
Abstract methods in Typescript
abstract class Animal { abstract makeSound(): void; } class Dog extends Animal { makeSound(): void { console.log('Woof!'); } }
An abstract method has no body and ends with a semicolon.
Classes with abstract methods must be declared abstract too.
Car provides its own startEngine method.abstract class Vehicle { abstract startEngine(): void; } class Car extends Vehicle { startEngine(): void { console.log('Car engine started'); } }
Circle implements area to calculate its area.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 Appliance { abstract turnOn(): void; } // Error: Cannot create instance of abstract class // const appliance = new Appliance();
This program shows an abstract class Employee with an abstract method calculateSalary. Two child classes implement this method differently. We create objects and print their salaries.
abstract class Employee { abstract calculateSalary(): number; } class FullTimeEmployee extends Employee { monthlySalary: number; constructor(monthlySalary: number) { super(); this.monthlySalary = monthlySalary; } calculateSalary(): number { return this.monthlySalary; } } class PartTimeEmployee extends Employee { hourlyRate: number; hoursWorked: number; constructor(hourlyRate: number, hoursWorked: number) { super(); this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked; } calculateSalary(): number { return this.hourlyRate * this.hoursWorked; } } const fullTimeEmployee = new FullTimeEmployee(3000); const partTimeEmployee = new PartTimeEmployee(20, 80); console.log('Full-time employee salary:', fullTimeEmployee.calculateSalary()); console.log('Part-time employee salary:', partTimeEmployee.calculateSalary());
Time complexity of calling an abstract method is the same as calling a normal method (O(1)).
Space complexity depends on the class instance size, not the abstract method itself.
Common mistake: Forgetting to implement the abstract method in child classes causes a compile error.
Use abstract methods when you want to enforce a contract for child classes, instead of optional overrides.
Abstract methods define a method without a body in an abstract class.
Child classes must implement all abstract methods.
Abstract classes cannot be instantiated directly.