Typescript - Human Inheritance
Typescript Human Inheritance
Create class "Human" which has two protected members:
⚫ name[type as string] and age[type as number]
⚫ constructor(): this initialises name and age.
⚫ Create another class "Employee" which extends "Human" and have three members:
⚫ department[type as string], batch[type as string] and role[type as string]
⚫ constructor(): this initialises parent class protected members, department, batch and role.
⚫ getInfo(): this dispalys name, age, department, batch and role of the employee in a specific format.
Name: person one Age: 21 Department: computer science Batch: 2019 Role: Trainee
class Human {
protected name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Employee extends Human {
private department: string;
private batch: string;
private role: string;
constructor(name: string, age: number, department: string, batch: string, role: string) {
super(name, age);
this.department = department;
this.batch = batch;
this.role = role;
}
getInfo(): void {
console.log(`Name: ${this.name}`);
console.log(`Age: ${this.age}`);
console.log(`Department: ${this.department}`);
console.log(`Batch: ${this.batch}`);
console.log(`Role: ${this.role}`);
}
}
// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();
// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.