DEV Community

PRIYA K
PRIYA K

Posted on

Constructor Overloading in java

read gfg,tutorialpoint,programmiz

Java supports constructor overloading, which allows a class to have more than one constructor with different parameter lists. The appropriate constructor is selected at compile time based on the arguments passed during object creation. Constructor overloading enables objects to be initialized in multiple ways, improving flexibility and code clarity.
Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.

Similar to Java method overloading, we can also create two or more constructors with different parameters. This is called constructor overloading.

When do we need Constructor Overloading?
Objects need to be initialized with different sets of data
Default values are required in some cases
Simplified object creation is desired for common use cases

Example:
The Thread class provides multiple constructors. For example:

  Thread t = new Thread("MyThread");
Enter fullscreen mode Exit fullscreen mode

Example

class Main {
  String language;
  // constructor with no parameter
  Main() {
    this.language = "Java";
  }
  // constructor with a single parameter
  Main(String language) {
    this.language = language;
  }
  public void getName() {
    System.out.println("Programming Language: " + this.language);
  }
  public static void main(String[] args) {
    // call constructor with no parameter
    Main obj1 = new Main();
    // call constructor with a single parameter
    Main obj2 = new Main("Python");
    obj1.getName();
    obj2.getName();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output
Programming Language: Java
Programming Language: Python

In the above example, we have two constructors: Main() and Main(String language).
Here, both the constructors initialize the value of the variable language with different values.
Based on the parameter passed during object creation, different constructors are called, and different values are assigned.
It is also possible to call one constructor from another constructor. To learn more, visit Java Call One Constructor from Another.

Note: We have used this keyword to specify the variable of the class. To know more about this keyword, visit Java this keyword.

If no arguments are required, the default constructor can be used. If a thread name is needed, a parameterized constructor is selected automatically.

Problem Without Constructor Overloading

Consider a class Box with only one constructor:

class Box {
    double width, height, depth;

    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }
    double volume() {
        return width * height * depth;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this case, the following statement is invalid:

Box box = new Box(); // Compile-time error
Enter fullscreen mode Exit fullscreen mode

The class does not support creating:

An empty box
A cube using a single value
Enter fullscreen mode Exit fullscreen mode

Example of Constructor Overloading
By adding multiple constructors, different initialization options become available.

class Box {
    double width, height, depth;
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    // No-argument constructor
    Box() {
        width = height = depth = 0;
    }
    // Constructor for cube
    Box(double len) {
        width = height = depth = len;
    }
    double volume() {
        return width * height * depth;
    }
}
// Driver class
public class Test {
    public static void main(String[] args) {
        Box mybox1 = new Box(10, 20, 15);
        Box mybox2 = new Box();
        Box mycube  = new Box(7);
        System.out.println("Volume of mybox1: " + mybox1.volume());
        System.out.println("Volume of mybox2: " + mybox2.volume());
        System.out.println("Volume of mycube: " + mycube.volume());
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Volume of mybox1: 3000.0
Volume of mybox2: 0.0
Volume of mycube: 343.0

Using this() in Constructor Overloading
The this() keyword is used to call one constructor from another constructor in the same class. It helps avoid code duplication and ensures consistent initialization.

class Box {
    double width, height, depth;
    int boxNo;
    Box(double w, double h, double d, int num) {
        width = w;
        height = h;
        depth = d;
        boxNo = num;
    }
    Box() {
        width = height = depth = 0;
    }
    Box(int num) {
        this(); // Calls the no-argument constructor
        boxNo = num;
    }
    public static void main(String[] args) {
        Box box1 = new Box(1);
        System.out.println(box1.width);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
0.0

Rules for Using this() in Constructors
Constructor calls must be the first statement in the constructor.
Recursive constructor calls are not allowed.
A constructor can call only one other constructor.

Invalid Example:

    Box(int num) {
    boxNo = num;
    this(); // Compile-time error
    }
Enter fullscreen mode Exit fullscreen mode

Note:
Constructors can be overloaded like methods, but they do not have return types.
If any constructor is defined, Java does not generate a default constructor.
Constructor overloading improves object initialization flexibility.
Overloading is resolved at compile time.

Constructor Overloading vs Method Overloading
Feature: Constructor Overloading
Purpose: Initialize objects
Return type: Not allowed
Name:Same as class
Invocation:new keyword

Feature: Method Overloading
Purpose:Define multiple behaviors
Return type:Required
Name: Any valid method name
Invocation:Method call

Top comments (0)