Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
Polymorphism, a core principle in object-oriented programming, allows objects of different classes to be treated as objects of a common superclass through inheritance. It enables a single interface to be used to represent different types. In TypeScript, polymorphism is achieved through inheritance, interfaces, and method overriding. Let's dive deeper into polymorphism in TypeScript:
Polymorphism in TypeScript is closely tied to inheritance. Subclasses can be treated as instances of their base class, allowing them to be used interchangeably.
javascriptclass Animal {
makeSound(): void {
console.log("Some sound");
}
}
javascriptclass Dog extends Animal {
makeSound(): void {
console.log("Woof!");
}
}
class Cat extends Animal {
makeSound(): void {
console.log("Meow!");
}
}
Subclasses can override methods of their base class, providing a different implementation while keeping the method signature intact.
javascriptfunction performSound(animal: Animal): void {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
performSound(dog); // Outputs: "Woof!"
performSound(cat); // Outputs: "Meow!"
javascriptfunction performSound(animal: Animal): void {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
performSound(dog); // Outputs: "Woof!"
performSound(cat); // Outputs: "Meow!"
Interfaces also enable polymorphism in TypeScript by allowing classes to implement common behavior defined in an interface.
javascriptinterface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
area(): number {
return this.width * this.height;
}
}
function getArea(shape: Shape): number {
return shape.area();
}
const circle = new Circle(5);
const rectangle = new Rectangle(4, 6);
console.log(getArea(circle)); // Outputs: 78.53981633974483
console.log(getArea(rectangle)); // Outputs: 24
Code Reusability: Common interfaces enable code reuse by allowing multiple classes to implement the same behavior.
Flexibility: Polymorphism allows for flexible and generic code that can work with different types of objects.
Maintainability: As new classes are added, they can fit into existing code that relies on the common interface.
In TypeScript, the method to be called is determined at runtime, which is known as dynamic binding. This enables the method of the actual object instance to be called, even when referenced through a base class or interface.
Polymorphism provides a powerful way to create flexible and maintainable code by allowing a single interface to represent different types of objects, facilitating code reuse and adaptability. Understanding and leveraging polymorphism is fundamental to effective object-oriented programming in TypeScript.