The Wayback Machine - https://web.archive.org/web/20240604014230/https://www.geeksforgeeks.org/constructor-overloading-java/
Open In App

Constructor Overloading in Java

Last Updated : 16 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called based on the parameters specified when a new is executed. 

When do we need Constructor Overloading?

Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading.

 For example, the Thread class has 8 types of constructors. If we do not want to specify anything about a thread then we can simply use the default constructor of the Thread class, however, if we need to specify the thread name, then we may call the parameterized constructor of the Thread class with a String args like this:

Thread t= new Thread (" MyThread "); 

Let us take an example to understand the need of constructor overloading. Consider the following implementation of a class Box with only one constructor taking three arguments.

// An example class to understand need of
// constructor overloading.
class Box
{
    double width, height,depth;

    // constructor used when all dimensions
    // specified
    Box(double w, double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }

    // compute and return volume
    double volume()
    {
        return width * height * depth;
    }
}

As we can see that the Box() constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box() constructor. 

For example, the following statement is currently invalid:

Box ob = new Box();

Since Box() requires three arguments, it’s an error to call it without them. Suppose we simply wanted a box object without initial dimension, or want to initialize a cube by specifying only one value that would be used for all three dimensions. From the above implementation of the Box class, these options are not available to us. These types of problems of different ways of initializing an object can be solved by constructor overloading. 

Example of Constructor Overloading

Below is the improved version of class Box with constructor overloading.

Java




// Java program to illustrate
// Constructor Overloading
class Box {
    double width, height, depth;
 
    // constructor used when all dimensions
    // specified
    Box(double w, double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }
 
    // constructor used when no dimensions
    // specified
    Box() { width = height = depth = 0; }
 
    // constructor used when cube is created
    Box(double len) { width = height = depth = len; }
 
    // compute and return volume
    double volume() { return width * height * depth; }
}
 
// Driver code
public class Test {
    public static void main(String args[])
    {
        // create boxes using the various
        // constructors
        Box mybox1 = new Box(10, 20, 15);
        Box mybox2 = new Box();
        Box mycube = new Box(7);
 
        double vol;
 
        // get volume of first box
        vol = mybox1.volume();
        System.out.println("Volume of mybox1 is " + vol);
 
        // get volume of second box
        vol = mybox2.volume();
        System.out.println("Volume of mybox2 is " + vol);
 
        // get volume of cube
        vol = mycube.volume();
        System.out.println("Volume of mycube is " + vol);
    }
}


Output

Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

Using this() in Constructor Overloading

this() reference can be used during constructor overloading to call the default constructor implicitly from the parameterized constructor. 

Below is the implementation of the above method:

Java




// Java program to illustrate role of this() in
// Constructor Overloading
public class Box {
    double width, height, depth;
    int boxNo;
 
    // constructor used when all dimensions and
    // boxNo specified
    Box(double w, double h, double d, int num)
    {
        width = w;
        height = h;
        depth = d;
        boxNo = num;
    }
 
    // constructor used when no dimensions specified
    Box()
    {
        // an empty box
        width = height = depth = 0;
    }
 
    // constructor used when only boxNo specified
    Box(int num)
    {
        // this() is used for calling the default
        // constructor from parameterized constructor
        this();
 
        boxNo = num;
    }
 
    public static void main(String[] args)
    {
        // create box using only boxNo
        Box box1 = new Box(1);
 
        // getting initial width of box1
        System.out.println(box1.width);
    }
}


Output

0.0

As we can see in the above program we called Box(int num) constructor during object creation using only box number. By using this() statement inside it, the default constructor(Box()) is implicitly called from it which will initialize the dimension of Box with 0. 

Note : The constructor calling should be first statement in the constructor body.

For example, the following fragment is invalid and throws compile time error.

Box(int num)
{
    boxNo = num;

    /* Constructor call must be the first
       statement in a constructor */
    this();  /*ERROR*/
}

Important points to be taken care of while doing Constructor Overloading 

  • Constructor calling must be the first statement of the constructor in Java.
  • If we have defined any parameterized constructor, then the compiler will not create a default constructor. and vice versa if we don’t define any constructor, the compiler creates the default constructor(also known as no-arg constructor) by default during compilation
  • Recursive constructor calling is invalid in Java.

FAQ in Constructor Overloading

1. Differentiate Constructors Overloading vs Method Overloading.

Answer:

Strictly speaking, constructor overloading is somewhat similar to method overloading. If we want to have different ways of initializing an object using a different number of parameters, then we must do constructor overloading as we do method overloading when we want different definitions of a method based on different parameters. 

Related Topics



Previous Article
Next Article

Similar Reads

Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Java Function/Constructor Overloading Puzzle
Predict the output of the program public class GFG { private GFG(Object o) { System.out.println("Object"); } private GFG(double[] d) { System.out.println("double array"); } public static void main(String[] args) { new GFG(null); } } Solution: The parameter passed to the constructor is the null object reference and arrays are ref
1 min read
Java Program to Show Inherited Constructor Calls Parent Constructor By Default
In java, there exists a very important keyword known as super() keyword in java which is widely used in java being object-oriented and hence inheritance comes into play. So whenever we use super keyword inside a child constructor then it calls the default parent constructor by itself. Example 1 Java Code // Java Program to Demonstrate Inherited con
2 min read
java.lang.reflect.Constructor Class in Java
java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constru
4 min read
Method Overloading in Java
In Java, Method Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding. In Method overloading c
9 min read
Overloading Variable Arity Method in Java
Here we will be discussing the varargs / variable arity method and how we can overload this type of method. So let us first understand what a variable arity method is and its syntax. A variable arity method also called as varargs method, can take a number of variables of the specified type. Note: Until version 1.4 there is no varargs method. It was
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
Java Program to Find Area of Rectangle Using Method Overloading
A rectangle is a simple flat figure in a plane. It has four sides and four right-angles. In a rectangle all four sides are not of equal length like a square, sides opposite to each other have equal length and both the diagonals of the rectangle have equal length. Method overloading allows different methods to have the same name, but different signa
2 min read
Java Program to Find Area of circle Using Method Overloading
A circle is a simple shape consisting of all the points in the plane that are equidistant from a point known as the center of the circle. In this article, we will learn how to find the area of the circle using the method overloading. Terminology: Method Overloading: Method overloading allows different methods to have the same name, but different si
3 min read
Java Program to Find Area of Square Using Method Overloading
A square is a simple flat shape in a plane, defined by four points at the four corners. It has four sides with equal length and four corners with right angles. Method Overloading: Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of in
3 min read
Article Tags :
Practice Tags :