TYPESCRIPT
TypeScript - Polymorphism
Create a class "Automobile" that has two protected properties and a method:
- fuelType and price
- initialize the properties using constructor
- printInfo(): displays "I am automobile" in console
- Now create another class "Car" which extends the above class and has two functions
- constructor: this initializes "fuelType" and "price" by invoking the base class constructor
- printInfo(): displays Fuel type and price of that object in a format specified below // overriding function
Fuel Type: <fuelType>
Price: <price>
Sample Output:
I am automobile
Fuel Type: Petrol
Price: 100
Note: Inputs are passed in the constructor of the class Car
Solution:
class Automobile {
protected fuelType: string;
protected price: number;
constructor(theFuelType: string, thePrice: number) {
this.fuelType = theFuelType;
this.price = thePrice;
}
printInfo() {
console.log("I am automobile");
}
}
class Car extends Automobile {
constructor(fuelType: string, price: number) {
super(fuelType, price);
}
printInfo(): void {
super.printInfo();
console.log("Fuel Type: " + this.fuelType + "\nPrice: " + this.price);
}
}
let newCarObject = new Car('Petrol',100)
newCarObject.printInfo()
Also check out - TypeScript Inheritance TypeScript Class
Comments
Post a Comment