Java Constructor overloading

(Last Updated On: March 6, 2019)

Learn constructor overloading in Java with simple coding example and uses.

Constructor Overloading

In java programming, constructor overloading means, a class can have more than one constructors with different number of parameters or with different data types.

Before moving further, recommend to read below topic.

We have seen a example of a class having multiple constructors in java. In fact, this is the constructor overloading that comes under compile time polymorphism in java oops.

Let’s understand by example, what does it mean that having constructors with different number of parameters or with different data types with same number of arguments.

Constructors having different number of parameters

In below class, these two constructors have different number of parameters.
A(int a, int b){}
A(int a ,int b, double c){}

Constructors having different data types with same number of parameters

Below two constructors have same number of parameters i.e. one, but, with different data types.
A(int a){}
A(double b){}

Given class.

 

Example of Constructor overloading in java

In below program, three Employee class constructors will be overloaded with different number of signatures. When we create different objects with different parameters, then respective matching constructor get called.

 

Output:
Employee Info:
ID: 0
Name: Not Available

Employee Info:
ID: 123
Name: Not Available
Employee Info:
ID: 123
Name: John

 

 

User of Constructor Overloading in Java

You might be wondering what is the use of constructor overloading in programs. Lets understand by with pseudo example.

We want to write a custom sort class to sort an integer array. And, we want to have two options as given below

  • sort array by default in ascending order
  • sort array with given range.

We can solve these problems using constructor overloading. We can send an array to a class during object creation i.e. to constructor of the class. and can overload another constructor that accept an int array and ranges (first index and second index).

See the pseudo java code

NOTE:

1)When an object of a class in java program is created then a constructor is called implicitly as constructor cannot be called explicitly. So, in above constructor overloading program example, respective overloaded constructors will be called at the time of creation of objects of the class Employee i.e. e1, e2 and e3.

2) Also, note that constructor overloading is compile time polymorphism as similar to java method overloading