Simple constructor overloading program in java with explanation

Answer: Constructor overloading in Java Programming is similar to method overloading in java code. When we create more than one constructors in a class with different number of parameters and types, it is called as constructor overloading.

For example, In below Java program 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.

Constructor overloading Java Program Example

 

 

Output:

Employee Info:
ID: 0
Name: Not Available

Employee Info:
ID: 123
Name: Not Available

Employee Info:
ID: 123
Name: John

NOTE: constructor overloading also comes under compile time polymorphism in Java programming 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

Read More