Java Constructors

In this post we will learn about Java Constructors.


Video coming soon!



Subscribe for more updates


Algorithm/Insights

A constructor is used for creating objects. The code for initializing class variables is added in a constructor.
A constructor is declared as follows:

For example, consider the following Person class which has 2 constructors defined below:

To create a Person object, we can call any of these constructors as follows:
Person person1 = new Person();
Person person2 = new Person("Saurabh", "Kumar", "IDeserve", "9876543210");

So, a constructor is like a method but there are differences between a constructor and a method:
1.    A constructor name is same as the class name whereas a method can be named as anything that follows method naming convention.
2.    No return type should be specified for a constructor.

Default Constructor:
If a class does not define any constructor, then the compiler provides a default constructor in the class. The default constructor has no arguments and calls the no argument constructor of the super class. A default constructor is added by the compiler to a class only if no constructor, parameterized or parameterless, is present in the class.

super:
super keyword is used for invoking super class constructor.
For example:
Consider Employee class which extends Person. In the constructor for Employee class, we do not need to add initialization statements for fields already in parent class. For this, we can use super as below:

If a constructor makes a call to super, then this call should be the first statement in the constructor otherwise it will be a compile time error.
If a call to super is not added to a constructor, then the complier implicitly adds a call to default super() constructor before the first statement in the constructor. Since Object is a super class of every class, if a class does not extend any class, the implicit call to super() added by the compiler refers to the super() constructor of Object class.
If invoking default super() constructor is all that is needed, then adding a super() call is not required.
If the super class does not have a default constructor, then explicit call to the super constructor must be made otherwise this will result in a compile time error. So, if we remove the no argument constructor Person() from Person class, then following code results in compiler error as shown:

this:
this refers to the current object. A call to this(..) is made if there is a requirement to invoke another constructor of the same class.
For example, if we need to add a constructor to the Person class that initializes only firstName and lastName then we can create it as follows:

Please write to us if you have any questions through the comments section.


Contribution

  • Sincere thanks from IDeserve community to Saurabh Kumar for compiling current post.

    Saurabh Kumar

    Ninja Programmer