w3resource

TypeScript Car Class with Protected Properties

TypeScript Classes and OOP : Exercise-19 with Solution

Write a TypeScript program that creates a class called Car with the following properties and methods:

  • protected make: string
  • protected model: string

The class should have a constructor that accepts make and model. Implement a method:

public getCarInfo(): string that returns a string containing the make and model of the car.

Make sure that the make and model properties are only accessible within the class and its subclasses.

Sample Solution:

TypeScript Code:

class Car {
  protected make: string;
  protected model: string;

  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }

  public getCarInfo(): string {
    return `Make: ${this.make}, Model: ${this.model}`;
  }
}
// Example usage:
const car = new Car("BMW", "X1");
console.log(car.getCarInfo());  

Explanations:

In the exercise above -

  • First we define a "Car" class with two protected properties, 'make' and 'model'.
  • The constructor accepts 'make' and 'model' and initializes these properties accordingly.
  • Next we implement a public method "getCarInfo()" that returns a string containing the make and model of the car.
  • The 'make' and 'model' properties are accessible only within the class and its subclasses, as requested.

Output:

"Make: BMW, Model: X1"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Student Class with Private and Protected Properties.
Next: TypeScript Animal Class with Protected and Private Properties.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-class-and-oop-exercise-19.php