What is Constructor overloading in java? explain with example

Constructor overloading in Java is similar to method overloading. When we create more than one constructors in a class with different number of parameters and types, it is called as constructor overloading in java oops. Note that constructor overloading is done in the same class and it comes under implementation of compile time polymorphism in java .

Constructor is a special method and have same name as class name. The class can have more that one constructors with different data types with same number of argument OR with different number of arguments. See below example with comments. Class name is A and multiple constructors have been written ( overloaded) and all constructors have same name as class name i.e. A.

 

 

Lets see java constructor overloading more with a complete practical example with output.

In below Java source code example, we have a class called Employee, having three overloaded constructors i.e. Employee(), Employee(int id) and Employee(int id, string name).

We know that when we create an object of a class then constructor gets called. So, In java program, if we create objects of the class with parameters then the respective overloaded constructor will be called. i.e.

Employee e1 = new Employee(); //object e1 will call Employee()constructor.
Employee e2 = new Employee(123); //object e2 will call Employee(int id)constructor.
Employee e3 = new Employee(123, “John”); //object e3 will call Employee(int id, string name) constructor.

 

Example of constructor overloading in Java

 

 

Output:

Employee Info:
ID: 0
Name: Not Available

Employee Info:
ID: 123
Name: Not Available

Employee Info:
ID: 123
Name: John

 

Use of constructor overloading in Java

You might be wondering why to use constructor overloading in java programs, what are the benefits of using it in real life programs etc. Here is the answer for this question.

  • We use constructor overloading to provide simplicity. In java polymorphism post , in section, “How polymorphism provides simplicity?”,  you can read , how in Paint class, constructor overloading provides simplicity.
  • You can read one use case real time scenario using constructor overloading that I have implemented in one of the project, in the post advantages of constructor overloading .   Syntax is in C++ but the concept is same as in java that you can understand easily.

 

NOTE: Constructor overloading in java , also comes under compile time polymorphism as same as method overloading.
One implementation of constructor overloading, you can see here in java AWT color class, where multiple constructors are overloaded: https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html