What is constructor overloading in Java?

Constructor

Constructor is a special type of method used for object initialization of a class.

Compiler provides a default constructor if we don’t have any constructor in the class. They are invoked implicitly.

There are 2 types of constructors:

  • Default constructors
  • Parameterized constructors

There are some rules for creating a constructor in Java:

  • Constructor name should be the same as the class name.
  • Constructor shouldn’t have any explicit return type.
  • Constructor cannot be abstract, static, final, and synchronized.

Constructor overloading

Constructor overloading involves having more than one constructor with different parameters.

This is done to make every constructor perform a specific task.

Differences in parameters make the compiler understand that every constructor is different from another.

Code

Let’s take a look at the code snippet below.

class Container
{
double length,breadth,height;
Container(double l, double b, double h)
{
length = l;
breadth = b;
height = h;
}
Container()
{
length=breadth=height=0;
}
Container(double side)
{
length=breadth=height=side;
}
double volume()
{
return length*breadth*height;
}
}
class Main
{
public static void main(String args[])
{
Container cuboid = new Container(3, 4, 8);
Container nonebox = new Container();
Container cube = new Container(12);
double vol;
vol = cuboid.volume();
System.out.println(" Volume of cuboid is " + vol + " cubic unit");
vol = nonebox.volume();
System.out.println(" Volume of nonebox is " + vol + " cubic unit");
vol = cube.volume();
System.out.println(" Volume of cube is " + vol + " cubic unit");
}
}

Explanation

  • In line 1, we create a class named Container.

  • In line 3, we declare variables of double type.

  • In lines 4 to 9, we create the first parameterized constructor in which we assign all double type parameters to the declared variables of the class respectively.

  • In lines 10 to 13, we create a second constructor with no parameters in which we assign 0 to all the variables of the class.

  • In lines 14 to 17, we create a third constructor with one double type parameter and assign the parameter to all the variables of the class.

  • In lines 19 to 22, we define a method which returns the volume of the container with the help of the values of the variables of the class.

  • In lines 25 and 27, we initialize a Main class and a main function.

  • In lines 29 to 31, we create the object of the Container class and initialize them with the help of constructors.

  • In lines 34 to 39, we call the method of Container class and displayed the value stored in the double type variable.