Java - Overloading - Constructors

Java

In this tutorial we will learn about constructors overloading in Java programming language.

We learned about constructors in the Class - Constructors tutorial. Feel free to check that out.

Constructor overloading is similar to Method Overloading.

What is Constructor overloading in Java?

In a Java class when we have more than one constructor with different parameter declaration then the constructors are said to be overloaded and the process is called constructor overloading.

Syntax

class NameOfTheClass {
  
  // constructor overloading

  NameOfTheClass() {
    // some code...
  }

  NameOfTheClass(list_of_params1) {
    // some code...
  }

  NameOfTheClass(list_of_params2) {
    // some code...
  }
}

Where, NameOfTheClass is the name of the class and it have 3 constructors sharing the same name as the class but with different parameter declaration.

Example #1:

In the following example we have the PackagingBox class. And we are going to initialise its dimensions using constructor overloading.

class PackagingBox {

  // member variables
  private double length;
  private double breadth;
  private double height;

  // constructor overloading
  
  // if dimensions not specified
  PackagingBox() {
    this.length = 0;
    this.breadth = 0;
    this.height = 0;
  }

  // if dimensions specified
  PackagingBox(double length, double breadth, double height) {
    this.length = length;
    this.breadth = breadth;
    this.height = height;
  }

  // method
  
  public void showDimensions() {
    System.out.println("Length: " + this.length);
    System.out.println("Breadth: " + this.breadth);
    System.out.println("Height: " + this.height);
  }

  public double getVolume() {
    return this.length * this.breadth * this.height;
  }
}

class ConstructorOverloadingExample {
  public static void main(String[] args) {
    // create object
    
    // no dimension is set
    PackagingBox myBox1 = new PackagingBox();

    System.out.println("Dimension of box 1:");
    myBox1.showDimensions();
    System.out.println("Volume of box 1: " + myBox1.getVolume());
    
    // setting dimension
    PackagingBox myBox2 = new PackagingBox(10, 20, 30);

    System.out.println("Dimension of box 2:");
    myBox2.showDimensions();
    System.out.println("Volume of box 2: " + myBox2.getVolume());
    
  }
}

Output:

$ javac ConstructorOverloadingExample.java 
$ java ConstructorOverloadingExample
Dimension of box 1:
Length: 0.0
Breadth: 0.0
Height: 0.0
Volume of box 1: 0.0
Dimension of box 2:
Length: 10.0
Breadth: 20.0
Height: 30.0
Volume of box 2: 6000.0