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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics