Polymorphism through interfaces
📖 Scenario: You are building a simple system to handle different types of notifications in an app. Each notification type should be able to send its message in its own way.
🎯 Goal: Create an interface called Notifier with a method send(). Then create two classes EmailNotifier and SMSNotifier that implement this interface. Finally, use polymorphism to call send() on both types of notifiers.
📋 What You'll Learn
Create an interface called
Notifier with a method send() that returns void.Create a class called
EmailNotifier that implements Notifier and its send() method prints 'Sending email notification'.Create a class called
SMSNotifier that implements Notifier and its send() method prints 'Sending SMS notification'.Create an array called
notifiers of type Notifier[] containing instances of EmailNotifier and SMSNotifier.Use a
for loop to call send() on each notifier in the notifiers array.Print the output of each
send() call.💡 Why This Matters
🌍 Real World
Many apps send notifications in different ways like email, SMS, or push notifications. Using interfaces and polymorphism helps manage these different types easily.
💼 Career
Understanding polymorphism and interfaces is key for writing flexible and maintainable code in TypeScript and many other programming languages.
Progress0 / 4 steps