Overloading Constructors in Java with Examples

In this article, we will learn what is constructor overloading with example and how to use this keyword to call one constructor from another constructor of the same class.
In addition to overloading normal methods, you can also overload constructor methods. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception.
A default constructor is useful for creating objects with a default initialization value. When you want to initialize the objects with different values in different instantiations, you can pass them as the arguments to constructors. And yes, you can have multiple constructors in a class — which is constructor overloading.
Let's demonstrates how to overload constructors with examples.

Overloading Constructors Example

Let's create a simple Box class with single constructor first:
class Box {
    double width;
    double height;
    double depth;

    // This is the constructor for Box.
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    // compute and return volume
    double volume() {
        return width * height * depth;
    }
}
As you can see, the Box(double w, double h, double d) constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box(double w, double h, double d) constructor. For example, the following statement is currently invalid and gives compiler error:
Box ob = new Box();
Since Box( ) requires three arguments, it’s an error to call it without them. This raises some important questions. What if you simply wanted a box and did not care (or know) what its initial dimensions were? Or, what if you want to be able to initialize a cube by specifying only one value that would be used for all three dimensions? As the Box class is currently written, these other options are not available to you.
Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it handles the situations just described. 
Here is a program that contains an improved version of Box that does just that:
package com.javaguides.corejava.basics.polymorphism;

public class OverloadingConstructors {
    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);
    }
}

/*
 * Here, Box defines three constructors to initialize the dimensions of a box
 * various ways.
 */
class Box {
    double width;
    double height;
    double 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 = -1; // use -1 to indicate
        height = -1; // an uninitialized
        depth = -1; // box
    }

    // constructor used when cube is created
    Box(double len) {
        width = height = depth = len;
    }

    // compute and return volume
    double volume() {
        return width * height * depth;
    }
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
As you can see, the proper overloaded constructor is called based upon the parameters specified when new is executed.

Using this keyword - invoke one constructor from another constructor

We should use this keyword to call one constructor from another constructor of the same class.
Use the explicit this qualifier when accessing fields inside instance methods or constructors to avoid ambiguity in referring to variable names.
Example: Let's create Circle class with overloaded constructors without this keyword:
package com.javaguides.corejava.basics.polymorphism;

public class OverloadingConstructors {
    public static void main(String[] s) {
        System.out.println(new Circle());
        System.out.println(new Circle(50, 100));
        System.out.println(new Circle(25, 50, 5));
    }
}

class Circle {
    private int xPos;
    private int yPos;
    private int radius;

    // three overloaded constructors for Circle
    public Circle(int x, int y, int r) {
        xPos = x;
        yPos = y;
        radius = r;
    }

    public Circle(int x, int y) {
        xPos = x;
        yPos = y;
        radius = 10; // default radius
    }

    public Circle() {
        xPos = 20; // assume some default values for xPos and yPos
        yPos = 20;
        radius = 10; // default radius
    }

    public String toString() {
        return "center = (" + xPos + "," + yPos + ") and radius = " + radius;
    }
}
Output:
center = (20,20) and radius = 10
center = (50,100) and radius = 10
center = (25,50) and radius = 5
As you can see, the compiler has resolved the constructor calls depending on the number of arguments. Did you notice that you are duplicating the code inside the three constructors? To avoid that code duplication—and reduce your typing effort—you can invoke one constructor from another constructor. Of the three constructors, the constructor taking x-position, y-position, and a radius is the most general constructor. The other two constructors can be rewritten in terms of calling the three argument constructors, like so:
package com.javaguides.corejava.basics.polymorphism;

public class OverloadingConstructors {
    public static void main(String[] s) {
        System.out.println(new Circle());
        System.out.println(new Circle(50, 100));
        System.out.println(new Circle(25, 50, 5));
    }
}

class Circle {
    private int xPos;
    private int yPos;
    private int radius;

    public Circle(int x, int y, int r) {
        xPos = x;
        yPos = y;
        radius = r;
    }

    public Circle(int x, int y) {
        this(x, y, 10); // passing default radius 10
    }

    public Circle() {
        this(20, 20, 10);
        // assume some default values for xPos, yPos and radius
    }

    public String toString() {
        return "center = (" + xPos + "," + yPos + ") and radius = " + radius;
    }
}
Output:
center = (20,20) and radius = 10
center = (50,100) and radius = 10
center = (25,50) and radius = 5
The output is exactly the same as for the previous program, but this program is shorter; you used this keyword to call one constructor from another constructor of the same class.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments