To better understand classes in TypeScript, my book club members and I learned about object-oriented programming. I got stuck on polymorphism, so I did some research and created some classes on my own.
If you find any mistakes, I would appreciate it if you could point them out in the comments below.
- What is Polymorphism?
- What are some sample codes and which part demonstrates Polymorphism?
What is Polymorphism?
Polymorphism is one of the methods in Object-Oriented Programming. Polymorphism literally means "many forms."
When extending classes from a base class/parent class, you can modify the behavior of an existing method in the derived/child class.
Sample Codes
class Animals {
animalName: string;
constructor(animalName: string) {
this.animalName = animalName;
}
move(animalName: string = "Animals"):string {
return `${animalName} can move.`
}
}
class Fish extends Animals {
constructor(animalName: string){
super(animalName);
}
move(animalName: string): string {
return `${animalName} swim.`
}
}
class Birds extends Animals {
constructor(animalName: string){
super(animalName);
}
move(animalName: string): string {
return `${animalName} fly.`
}
}
class Kangaroos extends Animals {
constructor(animalName: string){
super(animalName);
}
move(): string {
return `Kangaroos jump.`
}
}
const animals = new Animals("")
const clownfish = new Fish("clownFish");
const sparrow = new Birds("sparrows");
const kangaroos = new Kangaroos("Kangaroos");
console.log(animals.move())
console.log(clownfish.move("Clownfish"))
console.log(sparrow.move("Sparrows"))
console.log(kangaroos.move())
Polymorphism is demonstrated through the move() method, which can be modified in derived classes to provide different implementations. When you create a new object, it executes its own version of the move() method.
Top comments (0)