Abstract classes are a fundamental concept in object-oriented programming, and TypeScript provides robust support for them. These classes serve as blueprints for other classes but cannot be instantiated directly.
An abstract class is a base class from which other classes may be derived. It may contain abstract methods (methods without a body) and concrete methods (with implementation). Abstract classes are declared using the abstract
keyword.
Here's a basic example of an abstract class in TypeScript:
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}
In this example, Animal
is an abstract class with an abstract method makeSound()
and a concrete method move()
.
To use an abstract class, you must create a derived class that implements all abstract methods:
class Dog extends Animal {
makeSound(): void {
console.log("Woof! Woof!");
}
}
const dog = new Dog();
dog.makeSound(); // Output: Woof! Woof!
dog.move(); // Output: Moving...
While abstract classes and interfaces serve similar purposes, they have some key differences:
Abstract Classes | Interfaces |
---|---|
Can have implemented methods | Only method signatures, no implementation |
Can have constructors | Cannot have constructors |
A class can extend only one abstract class | A class can implement multiple interfaces |
Abstract classes are a powerful feature in TypeScript, enabling developers to create robust and flexible class hierarchies. They play a crucial role in implementing the polymorphism concept in object-oriented programming.
Mastering abstract classes in TypeScript is essential for building scalable and maintainable object-oriented applications. They provide a perfect balance between code reuse and enforcing a common structure across related classes.