Abstraction in TypeScript
Welcome to Abstraction
Welcome back! Previously, you explored polymorphism and how it empowers you to create flexible code structures using inheritance. In this session, we will take a step further into a crucial aspect of object-oriented programming: Abstraction.
Understanding Abstraction in TypeScript
TypeScript provides native support for abstraction through the use of the abstract keyword. Abstract classes in TypeScript allow you to define base classes that cannot be instantiated directly. These classes can include abstract methods — methods without an implementation — which must be implemented by any derived (sub) class. This enforces a contract for subclasses, ensuring that certain methods are always present and implemented.
By leveraging abstract classes and methods, you can create clear and maintainable code structures, encouraging consistency and reusability across your codebase.
1. Declaring Abstract Classes and Methods
In TypeScript, you can declare an abstract class using the abstract keyword. Abstract methods are also marked with abstract and do not include an implementation in the base class. Here’s how you can define an abstract class with abstract methods:
In this example, the Shape class is abstract and cannot be instantiated directly. The area and perimeter methods are declared as abstract, meaning any subclass of Shape must provide its own implementations. The getColor method is a concrete method that can be used by all subclasses.
2. Implementing the Methods in Derived Classes
Let’s create concrete classes that extend the abstract Shape class. Each subclass must implement the abstract methods defined in the base class.
Circle Class
The Circle class extends Shape and provides concrete implementations for the area and perimeter methods. The constructor initializes the circle’s radius and color, passing the color to the base class constructor using super.
