Use of Constructor Overloading in Java
In this class, We discuss the Use of Constructor Overloading in Java.
The reader should have prior knowledge of the constructor. Click Here.
We take an example and understand constructor overloading.
In the end, we understand the use of constructor overloading.
Example:
class A
{
int p;
A()
{
p=20;
}
A(int x)
{
p = x;
}
}
The above code contains two constructors.
Writing more than one constructor is called constructor overloading.
The signatures of constructors are different.
One constructor takes zero inputs, and the other takes one input.
Point to understand: which constructor is called during object creation?
We take a real-life example and understand the use of the constructor.
Take a cube and a cuboid.
We need to write a class to find the volume of a cube and a cuboid.
Both have the same formulae volume = length * width * height.
All sides of the cube are the same length.
Cuboids have different lengths, widths, and heights.
The below diagram shows the program for the volume of the cube.
The above class contains three constructors.
One constructor will give default values to length, width, and height.
The other constructor will give the values assigned by the user.
The third constructor will assign the same values to length, width, and height.
The class “test” will show the different ways to call all the constructors.
If the user needs to find the cube’s volume, he calls the third constructor.
The cube will have a length value.
The same length value should be assigned to width and height.
If the user needs to find the cuboid’s volume, he calls the second constructor.
Overloading gives users a chance to initialize instance variables in different ways.