Uses Of Constructor In Java

Snehatiwari
3 min readJul 8, 2021

this is my another post in which I will cover about the constructor basics to tell you about some interesting fact about constructor.

What is Constructor?

Basically constructor is a special type of member function of a class which is used for three reasons which is so important

  1. to initialize the object.
  2. to return the reference of the current calling object using this keyword.
  3. to initialize the parent class inherited properties.

As we know in java each time an object is created using new keyword. And the constructor is invoked at the time of object creation.

Why we can not give any return type to constructor ?

As we can see the second use of constructor because it is implicitly return the reference of the current calling object that is why we can not use any explicitly return type.

Rules of constructor:

  1. constructor of a class must have the same name as the class name.
  2. a constructor in java can not be abstract, final , static and synchronized.

Types of constructor :

In java to types of constructor is present

a. default constructor: A constructor that has no parameter is known as default constructor. If we do not define any constructor in a class so compiler automatic creates a default constructor.

b. parametrized constructor: A constructor that has parameters is known as parameterized constructor.

We can write more than one constructor in a single class that is called constructor overloading.

Lets see some example to understand those three points and uses of constructor:

Example 1:

so here we can see that on calling default constructor return the reference of currently calling object. And the this keyword is used to represent the reference of current object.

Example 2:

so As we know using new keyword object is created hence from this example we can see that only three object is created a3 and a4point the same object a2.

Example 3:

As we saw third point of use in this example we can see how a super constructor is used to call parent class properties.

I hope this post will be helpful for you.

Thankyou..

Sneha Tiwari

--

--