Constructor Overloading in Java
Need of constructor overloading
A constructor is a method in a class that is called as soon as the object of that class is created. Sometimes, we are required to initialize objects in different forms. This can be achieved using constructor overloading.
For example, sometimes we need to initialize an object with default values, and other times we need to declare them with specific values. In these cases, constructor overloading comes handy.
Consider a program below that creates a class Rectangle having three constructors:
- Rectangle()
- Rectangle(length)
- Rectangle(length, breadth)
As you can see in the program, these constructors have the same name they differ in the number of arguments they contain.
Source Code
// Creating a class |
Output:
Significance of this() in constructor overloading:
this() reference in Java is used to call the default constructor from a parameterized constructor. It is important to note here that this() must be the first statement inside a constructor.
For example, In the following program inside the constructor: Rectangle(length, breadth), We have used this() reference. As a result, the default constructor would be called and values of length and breadth both would be initialized to 0.
Source Code
// Creating a class |
Output:
Some of the points that must be taken care of while doing constructor overloading are the following:
- We are not allowed to do recursive constructor overloading in Java.
- this() reference must be the first statement inside the parameterized constructor.
Conclusion
In this article, we discussed constructor overloading in Java. We discussed various examples that illustrated its working. In the end, we saw the benefits of using this() in constructor overloading.
We believe that this article has helped to improve your OOPS concepts in the Java programming language.