Home / Programs / Typescript - Human Inheritance
Programming Example

Typescript - Human Inheritance

👁 113 Views
💻 Practical Program
📘 Step by Step Learning

Information & Algorithm

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.

Given Input:


Expected Output:

Name: person one
Age: 21
Department: computer science
Batch: 2019
Role: Trainee

Program Code

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();

Output

// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();

How to learn from this program

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.