Wednesday, December 14, 2022

Typescript inheritance example with code

 Typescript inheritance example with code

    Code example - https://typescript-bc7fcz.stackblitz.io


This video explains how to do inheritance in Typescript using examples. Code example - https://stackblitz.com/edit/typescript-bc7fcz?file=index.ts First we will create a parent class called Person. This class has two properties first name and last name. Write a constructor method to set these two properties. We will also have two methods. One for getting the full name and another describe method. Now the person class is ready. We are going to create an instance of this class using a new keyword. Using this instance we can call the two methods of Person class. Now we will see how to create a child class using Typescript inheritance. Typescript uses a keyword 'Extends' to inherit properties of another class. The constructor method of the child class should call super method , so that the parent constructor is invoked. Similar to parent class we can create an instance of child class . Since Student class is inherited from Person class, it can access its Parent class methods as well as its own methods. Why do we use inheritance? We can use it for Method Overriding (so runtime polymorphism can be achieved). We can use it for Code Reusability.

First we will create a parent class called Person. This class has two properties first name and last name. Write a constructor method to set these two properties. We will also have two methods. One for getting the full name and another describe method.

Now the person class is ready. We are going to create an instance of this class using a new keyword. Using this instance we can call the two methods of Person class.


Now we will see how to create a child class using Typescript inheritance. Typescript uses a keyword 'Extends' to inherit properties of another class. The constructor method of the child class should call super method , so that the parent constructor is invoked. Similar to parent class we can create an instance of child class . Since Student class is inherited from Person class, it can access its Parent class methods as well as its own methods.

Why do we use inheritance? We can use it for Method Overriding (so runtime polymorphism can be achieved). We can use it for Code Reusability.



No comments: