Start Coding

Topics

Abstract Classes in TypeScript

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.

What are Abstract Classes?

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.

Purpose of Abstract Classes

  • Define a common interface for subclasses
  • Provide default implementations for some methods
  • Enforce certain methods to be implemented by derived classes

Syntax and Usage

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().

Implementing Abstract Classes

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...
    

Key Considerations

  • Abstract classes cannot be instantiated directly
  • Derived classes must implement all abstract methods
  • Abstract classes can have constructor methods
  • They can contain both abstract and non-abstract (concrete) methods

Abstract Classes vs Interfaces

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

Best Practices

  • Use abstract classes when you want to provide a common base implementation for related classes
  • Prefer interfaces when you only need to define a contract for method signatures
  • Combine abstract classes with generics for more flexible and reusable code

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.

Conclusion

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.