Menu
Coddy logo textTech

ポリモーフィズムとは?

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`;
  }
}

もう一つの子クラスは以下の通りです:

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()); // ある動物が音を出します
console.log(dog.speak());    // Rexが吠えます
console.log(cat.speak());    // Whiskersが鳴きます

3つのオブジェクトすべてがspeak()メソッドに応答しますが、それぞれが独自の方法でそれを行います。

challenge icon

チャレンジ

親クラス Notification と2つの子クラスを持つ通知システムがあります。あなたのタスクは、それぞれのクラスに異なる実装を持つ send(message) メソッドを追加することです。

  1. EmailNotification クラスでは、このメソッドは次の文字列を返す必要があります: "Sending '(message)' via Email"
  2. SMSNotification クラスでは、このメソッドは次の文字列を返す必要があります: "Sending '(message)' via SMS"

チートシート

ポリモーフィズム(多態性)により、異なるクラスのオブジェクトが同じメソッドに対して異なる方法で応答できるようになります。JavaScriptでは、これは通常、子クラスが親クラスのメソッドをオーバーライドすることで実現されます。

メソッドを持つ親クラスを作成します:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
}

子クラスは、独自のメソッド実装で親メソッドをオーバーライドできます:

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

class Cat extends Animal {
  speak() {
    return `${this.name} meows`;
  }
}

各オブジェクトは、同じメソッドに対して異なる応答をします:

const animal = new Animal("Some animal");
const dog = new Dog("Rex");
const cat = new Cat("Whiskers");

console.log(animal.speak()); // Some animal makes a sound
console.log(dog.speak());    // Rex barks
console.log(cat.speak());    // Whiskers meows

自分で試してみよう

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()を使用する必要があります
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン