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. A class is a template or blueprint for creating objects. It is a logical entity.
A class can contain:
Syntax to declare a class:
class keyword is used declare a class in TypeScript. The syntax to create a class is given below:
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. The syntax of creating an object is given 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 which is used to expose the behavior of an object.
Advantage of Method
3. By Constructor
A constructor is used to initialized an object. In TypeScript, the constructor method is always defined with the name "constructor." In the constructor, the member of the class can be accessed by using this keyword.
Note: There is not necessary to always have a constructor in the class.
Example with constructor, method and object:
Reading attribute value of Student as: 101 Reading attribute value of Student as: Virat Kohli Function displays Student ID is: 101 Function displays Student ID is: Virat Kohli
Example without constructor:
Student ID: 101 Student Name: Virat Kohli