TypeScript Animal Class with Protected and Private Properties
TypeScript Classes and OOP : Exercise-20 with Solution
Write a TypeScript program that creates a class called Animal with the following properties and methods:
- protected name: string
- private age: number
The class should have a constructor that accepts name and age. Implement a method:
public introduce(): string that returns a string introducing the animal, including its name and age.
Ensure that the age property is accessible only within the class.
Sample Solution:
TypeScript Code:
class Animal {
protected name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public introduce(): string {
return `Hi, I'm ${this.name}, and I am ${this.age} years old.`;
}
}
// Example usage:
const animal = new Animal("Lion", 4);
console.log(animal.introduce()); // Output: Hi, I'm Lion, and I am 4 years old.
Explanations:
In the exercise above -
- First, we define an "Animal" class with a protected property 'name' and a private property 'age'.
- The constructor accepts 'name' and 'age' and initializes these properties accordingly.
- Next, we implement a public method "introduce()" that returns a string introducing the animal, including its name and age.
- The 'age' property is accessible only within the class, as requested.
Output:
"Hi, I'm Lion, and I am 4 years old."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Car Class with Protected Properties.
Next: TypeScript counter class with static methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics