Home / Programs / Typescript - Automobile Polymorphism
🚀 Programming Example

Typescript - Automobile Polymorphism

👁 156 Views
💻 Practical Program
📘 Step Learning

📌 Information & Algorithm

Typescript - Automobile 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: Price:


Sample Output:

I am automobile Fuel Type: Petrol Price: 100


Note: Inputs are passed in the constructor of the class Car

Note: Even though you got the exact output, the test cases will fail if you do not use the typescript OOPs concepts as mentioned in the problem statement.

💻 Program Code

class Automobile {
  protected fuelType: string;
  protected price: number;

  constructor(fuelType: string, price: number) {
    this.fuelType = fuelType;
    this.price = price;
  }

  printInfo(): void {
    console.log("I am automobile");
  }
}

class Car extends Automobile {
  constructor(fuelType: string, price: number) {
    super(fuelType, price);
  }

  // Overriding the printInfo method from the base class
  printInfo(): void {
    super.printInfo(); // Call the base class method
    console.log(`Fuel Type: ${this.fuelType}`);
    console.log(`Price: ${this.price}`);
  }
}

// Example usage:
const car = new Car("Petrol", 100);

// Calling the overridden method
car.printInfo();

                        

🖥 Program Output

// Example usage:
const car = new Car("Petrol", 100);

// Calling the overridden method
car.printInfo();
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.