Friday, 24 April 2015

Constructor overloading in Java

Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

Why Constructor overloading is needed

To know why constructor overloading is needed first let's be aware of one fact - if any constructor is defined for a class then Java won't define a default constructor. Default constructor for the class will only be inserted in case no constructor is defined.
In that case if there is a constructor defined like -

class ConstrOverLoading{
 private int i;
 private int j;
 //Constructor with 2 params
 ConstrOverLoading(int i, int j){
  this.i = i;
  this.j = j;
 }
}  

As it can be seen the ConstrOverLoading() constructor takes 2 parameters. In this case all the objects of this class must have two parameters, For example the statement
ConstrOverLoading obj = new ConstrOverLoading();
Will be invalid because, as already told, if any constructor is defined for a class then Java won't define a default constructor.

In these type of situations overloaded constructors are required.

A practical example would be arraylist class where there are 2 contructors related to initial capacity,

public ArrayList(int initialCapacity)
public ArrayList() {
    this(10);
}

In one of the case user can pass the initial capacity for the arraylist, in another case user can use the no-arg constructor and arraylist would have the default initial capacity of 10.

It is a common practice to use this with overloaded constructors and let only one of the constructor do the initialization, all the other constructors merely make a call to that constructor. Let's see it with an example.

Overloaded Constructor Example

class ConstrOverLoading {
 int a;
 double b;
 ConstrOverLoading(int a, double b){
  this.a = a;
  this.b = b;
 }
 ConstrOverLoading(int a){
  this(a, 0.0);
 }
 ConstrOverLoading(){
  this(0);
 }
 
}

It can be noticed here that only one of the contructor ConstrOverLoading(int a, double b) is doing any assignment other constructors are merely invoking that constructor through this(). This use of this helps in reducing the duplication of code.

Two points to note here

this() should be the first statement within the constructor in this case.

this() and super() can't be used with in the same constructor as it is required for both to be the first statement in the class.

That's all for this topic Constructor overloading in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Constructor in Java
  2. Constructor chaining in Java
  3. Method overloading in Java
  4. super in Java
  5. this in Java
  6. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

1 comment: