TypeScript Constructor Overloading
TypeScript Classes and OOP : Exercise-6 with Solution
Write a TypeScript program that creates a class called Student with properties name and roll number. Add constructor overloading to support multiple ways of initializing a Student object. Implement one constructor that takes both name and roll number as parameters and another constructor that takes only name, assuming the roll number is unknown.
Sample Solution:
TypeScript Code:
class Student {
// Properties
name: string;
rollNumber: number | undefined;
// Constructor with both name and roll number
constructor(name: string, rollNumber: number) {
this.name = name;
this.rollNumber = rollNumber;
}
// Constructor with only name (roll number is optional)
constructor(name: string) {
this.name = name;
}
}
// Create Student objects using different constructors
const studentWithRollNumber = new Student("Mateo Ishita", 11);
const studentWithoutRollNumber = new Student("Dvsch Gbjpiij");
// Access and print the properties
console.log("Student with Roll Number:");
console.log("Name:", studentWithRollNumber.name);
console.log("Roll Number:", studentWithRollNumber.rollNumber);
console.log("\nStudent without Roll Number:");
console.log("Name:", studentWithoutRollNumber.name);
console.log("Roll Number:", studentWithoutRollNumber.rollNumber); // This will be undefined
Explanations:
In the exercise above -
- First, we define the "Student" class with properties 'name' and 'rollNumber'.
- Next we provide two constructors for the "Student" class: one that takes both 'name' and 'rollNumber' as parameters and another that takes only 'name'. In the second constructor, we assume that 'rollNumber' is optional.
- Depending on which constructor is used, the 'rollNumber' property will either be initialized with the provided value or remain 'undefined'.
- Finally, we create two "Student" objects, one using each constructor, and access/print their properties to demonstrate constructor overloading.
Output:
"Student with Roll Number:" "Name:" "Mateo Ishita" "Roll Number:" 11 " Student without Roll Number:" "Name:" "Dvsch Gbjpiij" "Roll Number:" undefined
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Basic Constructor.
Next: TypeScript Derived Class Constructor.
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