TypeScript Student Class with Private and Protected Properties
TypeScript Classes and OOP : Exercise-17 with Solution
Write a TypeScript class called Student with the following properties and methods:
- private name: string
- protected studentId: number
The class should have a constructor that accepts a name and student ID. Implement a method:
public displayInfo(): void that displays the student's name and ID.
Make sure that the studentId property is accessible only within the class and its subclasses.
Sample Solution:
TypeScript Code:
class Student {
private name: string;
protected studentId: number;
constructor(name: string, studentId: number) {
this.name = name;
this.studentId = studentId;
}
public displayInfo(): void {
console.log(`Student Name: ${this.name}, Student ID: ${this.studentId}`);
}
}
// Example usage:
const student = new Student("Piri Lily", 12);
student.displayInfo();
Explanations:
In the exercise above -
- First, we define a "Student" class with a private property 'name' and a protected property 'studentID'.
- The constructor accepts a 'name' and a 'studentID' and initializes the properties accordingly.
- Next we implement a public method "displayInfo()" that displays the student's name and ID.
- The 'studentID' property is accessible only within the class and its subclasses, as requested.
Output:
"Student Name: Piri Lily, Student ID: 12"
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Geometric Shapes - Abstract Classes and Inheritance.
Next: TypeScript BankAccount Class with Private and Protected Properties.
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://w3resource.com/typescript-exercises/typescript-class-and-oop-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics