In object-oriented programming languages like Java, classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties. In terms of OOPs, a class is a template or blueprint for creating objects. It is a logical entity.
A class definition can contain the following properties:
Syntax to declare a class
A class keyword is used to declare a class in TypeScript. We can create a class with the following syntax:
Creating an object of class
A class creates an object by using the new keyword followed by the class name. The new keyword allocates memory for object creation at runtime. All objects get memory in heap memory area. We can create an object as below.
Object initialization means storing of data into the object. There are three ways to initialize an object. These are:
1. By reference variable
2. By method
A method is similar to a function used to expose the behavior of an object.
Advantage of Method
3. By Constructor
A constructor is used to initialize an object. In TypeScript, the constructor method is always defined with the name "constructor." In the constructor, we can access the member of a class by using this keyword.
Note: It is not necessary to always have a constructor in the class.
Example with constructor, method and object:
Example without constructor
It is a technique which is used to hide the internal object details. A class can control the visibility of its data members from the members of the other classes. This capability is termed as encapsulation or data-hiding. OOPs uses the concept of access modifier to implement the encapsulation. The access modifier defines the visibility of class data member outside its defining class.
TypeScript supports the three types of access modifier. These are:
To read more information about the access modifier, click here.