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
doubletype. -
In lines 4 to 9, we create the first parameterized constructor in which we assign all
doubletype 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
doubletype 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
containerwith the help of the values of the variables of the class. -
In lines 25 and 27, we initialize a
Mainclass and amainfunction. -
In lines 29 to 31, we create the object of the
Containerclass and initialize them with the help of constructors. -
In lines 34 to 39, we call the method of
Containerclass and displayed the value stored in thedoubletype variable.