If I have a class B that inherits from class A and overrides one of its method, and i have, in TypeScript:
const a: A = new A();
(B a).toto();
Why the toto()
method that will be called is the one implemented in the parent class (ie A)?
- In TypeScript, I have a class called
Drug
that has aname
and aneffiency
, and a methodupdateEfficiency()
that decreases efficiency by 1:
class Drug {
name: string;
efficiency: number;
constructor(name: string, efficiency: number) {
this.name = name;
this.efficiency = efficiency;
}
updateEfficiency() {
this.efficiency -= 1;
}
}
- I have another class called
BottleOfWine
that inherits fromDrug
class and overrides theupdateEfficiency()
method:
class BottleOfWine extends Drug {
constructor(efficiency: number) {
super(DrugNames.OLD_BOTTLE_OF_WINE, efficiency);
}
updateEfficiency() {
this.efficiency -= 2;
}
}
- I have a third class called
Inventory
which contains an array ofDrug
, and a methodupdateAll()
that updates the efficiency of all the drugs:
class Inventory {
drugs: Drug[];
constructor(drugs: Drug[]) {
this.drugs = drugs;
}
updateAll() {
this.drugs.forEach((drug) => {
switch (drug.name) {
case "Old bottle of wine":
// here I expect to call the child method that decreases the efficiency by 2,
// but the parent class is called instead
(drug as OldBottleOfWine).updateEfficiency();
break;
case "Insulin vial":
// nothing to do
break;
}
});
}
}
On the updateAll()
method, I want, depending on the name of the drug, to cast the drug
object into a more specific object (child) and call the method of the child class.
- Example:
const inventory = new Inventory([new Drug("Old bottle of wine", 10)])
inventory.updateAll();
console.log(inventory.drugs[0].efficiency); // I expected 8 (ie 10 - 2), but got 9 (ie 10 - 1)
How could you explain it?
New contributor
user25018137 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.