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:

  1. Non-Parameterized constructor
  2. Parameterized constructor

Non-Parameteraized constructor:

        These kind of constructor does not have parameter. These are of types as:

  1. Default constructor / implicit constructor
  2. Explicit constructor

Implicit 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.

Syntax :


Explicit constructor:

                Explicit constructor is made by the programmer.

Syntax:

 

Parameterised constructor:

It is created by the programmer to initialize instance variable. Parameterized constructor have parameters as argument.

Syntax:

Lets understand with simple example addition of two variables:

 

Hope you have learned something new today, keep Learning. If you want to learn more about the classes please do check out my blog on What is and how to use classes in JAVA? 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *