The Wayback Machine - https://web.archive.org/web/20240707221935/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.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
Invalid Method Overloading in Java
Overloaded methods are those which belong to the same class, having the same name but different arguments. The concept of method overloading came from polymorphism. Literally "poly" means many and "morphism' means form. Consider a real-life example of water as polymorphic because it can take many forms (Solid, Liquid, and gas). Similarly, in java,
4 min read
Automatic Type Promotion in Overloading in Java
Before going into the actual topic, first, we need to know about method overloading and type promotions. What is Method Overloading?When a class consists of more than one method with the same name but with different signatures and return types, then we call those overloaded methods, and the process is called method overloading. Example: void method
6 min read
Method Overloading in Different Classes in Java
Methods of a class said to be overloaded if Both declared in the same class, orBoth inherited by a class, orOne declared and one inherited And have the same name but a different signature. Refer to this article, Different ways of Method Overloading in Java, for a basic understanding of method overloading. The below programs demonstrate the same. Ca
3 min read
GFact 48 | Overloading main() in Java
Consider the below Java program. // A Java program with overloaded main() import java.io.*; public class Test { // Normal main() public static void main(String[] args) { System.out.println("Hi Geek (from main)"); Test.main("Geek"); } // Overloaded main methods public static void main(String arg1) { System.out.println("Hi,
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg