Inheritance & Polymorphism in TypeScript (Live Playground)
In this tutorial, we will explore inheritance and polymorphism in TypeScript, which are essential concepts in advanced object-oriented programming (OOP).
Inheritance
Inheritance is a mechanism that allows you to create a new class based on an existing one. The new class is called a subclass, and the existing one is called a superclass. Inheritance allows you to reuse code and create more maintainable applications.
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Max');
dog.speak(); // Max barks.
Polymorphism
Polymorphism is a concept that allows objects of different classes to be treated as objects of a common superclass. Polymorphism is often used in combination with inheritance to create more flexible and reusable code.
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}
class Cat extends Animal {
speak(): void {
console.log(`${this.name} meows.`);
}
}
const animals: Animal[] = [new Dog('Max'), new Cat('Molly')];
animals.forEach(animal => animal.speak());
// Max barks.
// Molly meows.
Method Overriding
Method overriding is a technique that allows a subclass to provide a different implementation for a method that is already defined in its superclass. This enables polymorphism and allows you to create more flexible and reusable code.
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Max');
dog.speak(); // Max barks.
Conclusion
In this tutorial, we have explored inheritance and polymorphism in TypeScript, which are essential concepts in advanced object-oriented programming (OOP). As you continue learning TypeScript, make sure to practice using inheritance, polymorphism, method overriding, and other OOP techniques to create more flexible, reusable, and maintainable code in your applications.