Why constructor is needed?
It can be a slow process to initialize all variables of a class, each time when an object is created. Because the requirement of initialization is very common, JAVA allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of constructor.
What is constructor?
- A constructor initializes an object immediately upon creation and it has the same name as class in which it resides.
- It is syntactically similar to a method. But it has no return type, not even void.
- This is because the implicit return type of a class constructor is class type itself.
- It is constructor job to initialize the variable of an object so that the code creating an instance will have initialized.
We can categorize constructor in two ways:
- Non-Parameterized constructor
- Parameterized constructor
These kind of constructor does not have parameter. These are of types as:
- Default constructor / implicit constructor
- Explicit constructor
We will not make this type constructor. It is made itself by class, when we will not make any constructor then only class create this type constructor.
Explicit constructor is made by the programmer.
It is created by the programmer to initialize instance variable. Parameterized constructor have parameters as argument.
Lets understand with simple example addition of two variables: