ポリモーフィズムとは?
CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 35/56。
ポリモーフィズムは、異なるクラスのオブジェクトが同じメソッドに異なる方法で応答できるようにする、オブジェクト指向プログラミングの基本原則です。
JavaScriptでは、ポリモーフィズムは、子クラスが親クラスのメソッドをオーバーライドするときに最もよく見られます。
speak()メソッドを持つシンプルな親クラスを作成しましょう:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}では、Animalを拡張する子クラスを作成しましょう:
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}もう1つの子クラスです。
class Cat extends Animal {
speak() {
return `${this.name} meows`;
}
}各子クラスはspeak()メソッドをそれぞれ異なる方法で実装します。これがポリモーフィズムの実例です!
これで、異なるオブジェクトを作成し、それぞれに同じメソッドを呼び出せるようになりました:
const animal = new Animal("Some animal");
const dog = new Dog("Rex");
const cat = new Cat("Whiskers");
console.log(animal.speak()); // Some animal が音を出す
console.log(dog.speak()); // Rex が吠える
console.log(cat.speak()); // Whiskers がニャーと鳴く3つのオブジェクトはすべてspeak()メソッドに応答しますが、それぞれ独自の方法で応答します。
チャレンジ
親クラス Notification と2つの子クラスを持つ通知システムがあります。あなたの課題は、それぞれの子クラスに異なる実装の send(message) メソッドを追加することです。
EmailNotificationclass では、メソッドは文字列 "Sending '(message)' via Email" を返す必要がありますSMSNotificationclass では、メソッドは文字列 "Sending '(message)' via SMS" を返す必要があります
自分で試してみよう
import { EmailNotification } from './email-notification.js';
import { SMSNotification } from './sms-notification.js';
// テストコード - 変更しないでください
const email = new EmailNotification();
const sms = new SMSNotification();
console.log(email.send("Hello!")); // EmailNotificationのsend()を使用するはずです
console.log(sms.send("Hello!")); // SMSNotificationのsend()を使用するはずですこのレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: JavaScriptオンラインコンパイラ