"is-a" 関係
CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 25/56。
「is-a」関係は、継承がいつ適切であるかを判断するための簡単なテストです。もし「X is a Y」と言ってそれが正しく聞こえるなら、恐らくXはYから継承すべきです。
正解(継承を使用する):
- 「犬は動物である」 →
class Dog extends Animal
- 「車は乗り物である」 →
class Car extends Vehicle
- 「教科書 は 本 である」 →
class Textbook extends Book
不適切(継承を使用しないでください):
- 「Driver は Car である」 → いいえ、運転手は車を使用します
- 「車輪は車である」 → いいえ、車輪は車の一部です
- 「学生はクラスルームである」→ いいえ、学生はクラスルームの中にいます
例えば、2つのオブジェクトを考えてみましょう:
// ベースクラス - それらすべてが何であるか
class Book {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
read() {
console.log(`Reading ${this.title} by ${this.author}`);
}
}
// NovelはBookの一種です(正しい継承)
class Novel extends Book {
constructor(title, author, pages, genre) {
super(title, author, pages);
this.genre = genre;
}
}
// クラスの使用
const fiction = new Novel("1984", "George Orwell", 328, "Dystopian");
fiction.read(); // "Reading 1984 by George Orwell" - Bookから継承
チャレンジ
ElectronicDeviceクラスとSmartphoneクラスが与えられています。Smartphoneは、追加機能を備えたElectronicDeviceの一種です。あなたのタスクは、ブランドが"Samsung"、モデルが"Galaxy S23"であるmyPhoneオブジェクトを作成することです。
チートシート
「is-a」関係は、継承がいつ理にかなっているかを判断するためのテストです。「XはYである」と言って正しく聞こえるなら、XはYを継承すべきです。
正しい例(継承を使用する):
- 「犬は動物である」 →
class Dog extends Animal - 「車は乗り物である」 →
class Car extends Vehicle - 「教科書は本である」 →
class Textbook extends Book
間違った例(継承を使用しない):
- 「ドライバーは車である」 → いいえ、ドライバーは車を使います
- 「車輪は車である」 → いいえ、車輪は車の一部です
- 「学生は教室である」 → いいえ、学生は教室の中にいます
例:
// 基底クラス
class Book {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
read() {
console.log(`Reading ${this.title} by ${this.author}`);
}
}
// 小説(Novel)は本(Book)である(正しい継承)
class Novel extends Book {
constructor(title, author, pages, genre) {
super(title, author, pages);
this.genre = genre;
}
}
const fiction = new Novel("1984", "George Orwell", 328, "Dystopian");
fiction.read(); // "Reading 1984 by George Orwell" - Bookから継承
自分で試してみよう
import { ElectronicDevice } from './electronicDevice.js';
import { Smartphone } from './smartphone.js';
// TODO: ブランドが "Samsung"、モデルが "Galaxy S23" の `myPhone` オブジェクトを作成してください。
// テスト用コード - 変更しないでください
console.log(myPhone.turnOn()); // "Samsung Galaxy S23 is now ON" と出力されるはずですこのレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。