Constructor Overloading in Java

Constructor overloading in Java is the process similar to method overloading which means with in a class you can have more than one constructor where the constructors differ in the number of parameters.

What is the use of having overloaded constructor

Constructor overloading in Java brings the flexibility of initializing the object as per your need. For example in ArrayList class there is a no-arg constructor which initializes the ArrayList with the default capacity and there is another constructor where initial capacity can be passed as a parameter to initialize ArrayList with the required initial capacity.

Another scenario where constructor overloading in Java helps is to provide a no-arg constructor when there is already a parameterized constructor.
Java implicitly inserts a default no-arg constructor if no constructor is provided in the class. If you provide a constructor yourself then this default no-arg constructor is not provided automatically.

In this class there is a paramterized constructor so default no-arg constructor is not provided automatically by Java. Thus the statement ConstructorDemo cd = new ConstructorDemo(); results in compile time error “The constructor ConstructorDemo() is undefined

In such scenario you can provide more than one constructor to make your object initialization flexible as per your requirement. Like in the above example you can also have a default no-arg constructor along with the parameterized constructor.

Constructor overloading example

Here is an example of constructor overloading where we have an array of type Object. The array is created with the default capacity in the no—arg constructor if no initial capacity is passed. In case initial capacity is passed constructor with initial capacity as parameter is invoked to create an array with passed initial capacity.

Output

Constructor overloading in Java best practices

In case of having multiple constructors you should be doing the task of initialization in one of the constructor. All the other constructors should ultimately call that constructor for initialization using this keyword.

An example will help to clear it. Consider the scenario where you have 3 fields in your class and you want to give option to initialize all of them or two of them or only a single one or none.

Output

In the example you can see that the initialization is done only by the following constructor-

All the other overloaded constructors are progressively calling this constructor to get the object initialization done.
That’s all for the topic Constructor Overloading in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.