Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
Runtime polymorphism, also known as dynamic polymorphism, is a fundamental concept in object-oriented programming that allows objects of different classes to respond to the same method call in a way that's appropriate for their specific type.
In TypeScript, runtime polymorphism is achieved through method overriding, where subclasses implement methods defined in a base class or interface. The method to be called is determined at runtime based on the actual object type.
Here's a detailed explanation of runtime polymorphism in TypeScript:
You start by defining a base class or an interface that includes method declarations.
javascriptabstract class Shape {
abstract area(): number;
}
The Shape class contains an abstract method area, which is meant to be overridden by subclasses.
Subclasses extend the base class and provide their own implementations of the methods defined in the base class.
javascriptclass Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
area(): number {
return this.width * this.height;
}
}
The Circle and Rectangle classes extend the Shape class and provide their own implementations of the area method.
At runtime, you can create instances of the subclasses and call the area method on these objects. The method that gets executed depends on the actual type of the object.
javascriptconst circle = new Circle(5);
const rectangle = new Rectangle(4, 6);
console.log(circle.area()); // Calls the Circle's implementation.
console.log(rectangle.area()); // Calls the Rectangle's implementation.
The actual area method that is executed is determined at runtime based on the object's type. This is runtime polymorphism in action.
Runtime polymorphism is a powerful mechanism in object-oriented programming that allows you to write flexible and extensible code by letting different objects respond to the same method call differently, depending on their types. This enables code reusability and promotes clean, object-oriented design.