In this article, We are learn Inheritance and Constructor.
- TypeScript supports the concept of Inheritance.
- Inheritance is the ability of a program to create new classes from an existing class.
- The class that is extended to create newer classes is called the parent class/super class.
- The newly created classes are called the child/sub classes.
- A class inherits from another class using the ‘extends’ keyword.
- Child classes inherit all properties and methods except private members and constructors from the parent class.
- There are 5 types of inheritance:
1.Single Inheritance
2.Multilevel Inheritance
3.Multiple Inheritance
4.Hybrid Inheritance
5.Hierarchical Inheritance
class child_class_name extends parent_class_name
Why use inheritance?
- We can use it for Method Overriding (so runtime polymorphism can be achieved).
- We can use it for Code Reusability.
Note: TypeScript supports only single and multilevel inheritance. It doesn't support multiple, hierarchical, and hybrid inheritance.
1.Single Inheritance
- Single inheritance can inherit properties and behavior from at most one parent class.
- It allow a derived/subclass to inherit the properties and behavior of a base class that enable the code reusability as well as we can add new features to the existing code.
2.Multilevel Inheritance
- When a derived class is derived from another derived class, then this type of inheritance is known as multilevel inheritance.
- Thus, a multilevel inheritance has more than one parent class.
Example:
Access Modifiers:
- The access modifiers are used for controlling the visibility or availability of its data members.
- There are three types of access modifiers in TypeScript: public, private and protected.
1.Public -
- By default members (properties and methods) of TypeScript class are public - so you don’t need to prefix members with the public keyword.
- Public members are accessible everywhere without restrictions.
2.Private -
- A private member cannot be accessed outside of its containing class.
- Private members can be accessed only within the class.
3.Protected -
- A protected member cannot be accessed outside of its containing class. P
- Protected members can be accessed only within the class and by the instance of its sub/child class.
Example of Access Modifier:
Constructor:
- In TypeScript, the constructor method is always defined with the name "constructor".
- Constructors are identified with the keyword "constructor".
- A Constructor is a special type of method of a class and it will be automatically invoked when an instance of the class is created.
- A class may contain at least one constructor declaration.
- If a class has no constructor, a constructor is provided automatically.
- A Class can have any number of constructors.
- When you are using the attribute public or private with constructor parameters, a field is automatically created, which is assigned the value.
constructor () {
// statement
}
Example:
Thank you.....