チャレンジ:extendsとsuper()を使ったクラス継承の実装
メニューを表示するにはスワイプしてください
課題
さまざまな種類の車両を管理する運輸管理システムを開発しています。各車両には make(メーカー)、model(モデル)、year(年式)が設定されています。電気自動車の場合は、さらに batteryCapacity(バッテリー容量)も管理する必要があります。継承を利用して、一般的な Vehicle クラスから電気自動車専用のクラスを拡張します。
ElectricVehicleクラスを継承するVehicleクラスを作成する;ElectricVehicleのコンストラクタはmake、model、year、batteryCapacityを受け取る;- 親クラスの初期化には
super()を使い、make、model、yearを初期化する; getDetailsにElectricVehicleメソッドを追加し、VehicleのgetDetailsメソッドをオーバーライドする。このメソッドではsuper.getDetails()を呼び出し、batteryCapacityの情報を追加する。フォーマットは次の通り:"{make} {model} ({year}) with a battery capacity of {batteryCapacity} kWh."。
12345678910111213141516171819202122232425262728293031class Vehicle { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } getDetails() { return `${this.make} ${this.model} (${this.year})`; } } class ElectricVehicle _____ _____ { _____(make, model, year, _____) { _____(_____, _____, _____); this.batteryCapacity = batteryCapacity; } _____() { return `${super._____} with a battery capacity of ${ _____._____ } kWh.`; } } // Testing const vehicle = new Vehicle('Toyota', 'Camry', 2020); console.log(vehicle.getDetails()); // Expected: Toyota Camry (2020) const electricVehicle = new ElectricVehicle('Tesla', 'Model 3', 2021, 75); console.log(electricVehicle.getDetails()); // Expected: Tesla Model 3 (2021) with a battery capacity of 75 kWh.
ElectricVehicleを継承するクラスVehicleの定義;ElectricVehicleのコンストラクタでは、batteryCapacity、make、modelの後にyearパラメータを追加;- 親クラスのコンストラクタ呼び出しには
super(make, model, year)を使用し、make、model、yearを初期化; batteryCapacityをElectricVehicleのプロパティとして設定;getDetailsにElectricVehicleメソッドを定義し、VehicleのgetDetailsメソッドをオーバーライド;getDetails内でsuper.getDetails()を利用して親クラスの詳細を取得し、バッテリー容量の情報を返却文字列に追加。
12345678910111213141516171819202122232425262728293031class Vehicle { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } getDetails() { return `${this.make} ${this.model} (${this.year})`; } } class ElectricVehicle extends Vehicle { constructor(make, model, year, batteryCapacity) { super(make, model, year); this.batteryCapacity = batteryCapacity; } getDetails() { return `${super.getDetails()} with a battery capacity of ${ this.batteryCapacity } kWh.`; } } // Testing const vehicle = new Vehicle('Toyota', 'Camry', 2020); console.log(vehicle.getDetails()); // Output: Toyota Camry (2020) const electricVehicle = new ElectricVehicle('Tesla', 'Model 3', 2021, 75); console.log(electricVehicle.getDetails()); // Output: Tesla Model 3 (2021) with a battery capacity of 75 kWh.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 15
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 15