Table of contents
1.
Introduction
2.
What is Constructor Overloading?
3.
When Do We Need Constructor Overloading?
4.
Need for Constructor Overloading
4.1.
Implementation
5.
Example of Constructor Overloading
5.1.
Implementation  
5.2.
Java
6.
Use of this() in Constructor Overloading
6.1.
Example
7.
Benefits of Constructor Overloading in Java
8.
Points to Remember While Doing Constructor Overloading
9.
Difference Between Constructor Overloading and Method Overloading in Java
10.
Frequently Asked Questions
10.1.
What is constructor overloading?
10.2.
What is overriding vs overloading constructor?
10.3.
 What is constructor overriding in Java?
10.4.
What is the constructor and destructor?
11.
Conclusion
Last Updated: Dec 1, 2024
Easy

Constructor Overloading In Java

Author Akshit Pant
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, constructors play a pivotal role in initializing objects when they are created. Constructor overloading is a powerful feature that allows a class to have more than one constructor, each with different parameters. This enables developers to create objects in various ways, providing flexibility in object initialization and enhancing code readability.

Constructor overloading helps streamline object creation by offering multiple ways to initialize an object based on the provided arguments. This technique not only simplifies the code but also improves its maintainability by allowing different initialization scenarios within the same class.

Constructor Overloading In Java

So, let us start reading about how Constructor Overloading works in Java.

Also read, Swap Function in Java

What is Constructor Overloading?

Constructor overloading in Java is a feature that allows a class to have more than one constructor with different parameter lists. This means that you can define multiple constructors with different sets of parameters, enabling you to create objects in various ways.

Examples of valid constructors for a class (say getDimension class) include:

getDimension (int length);
getDimension (int length, int breadth);
getDimension (String height, int h);

When Do We Need Constructor Overloading?

  • Multiple Initialization Scenarios: When you need to create objects in different ways depending on the available data, constructor overloading allows for various initialization options.
  • Flexibility in Object Creation: When you want to provide flexibility for object creation by allowing users of the class to initialize objects with different sets of parameters.
  • Default Values: When you want to provide default values for some object properties while allowing other properties to be initialized explicitly.
  • Improved Code Readability: When you want to avoid complex initialization logic within a single constructor, constructor overloading can simplify the code by offering distinct constructors for different use cases.
  • Enhanced Code Maintainability: When you need to maintain clear and organized code by separating different initialization scenarios, making it easier to understand and modify.
  • Backward Compatibility: When updating a class and adding new initialization options without breaking existing code that relies on older constructors.

Need for Constructor Overloading

It's sometimes necessary to initialize an object in a variety of methods. Constructor overloading can be used to accomplish this.

Let's look at an example to see why constructor overloading is required. Consider the following implementation of a class myClass with only one constructor taking three arguments(length, breadth, height).

Implementation

class myClass
{
    float length, breadth, height;

    myClass(float l, float b, float h)  // constructor with 3 parameters
    {
        length = l;
        breadth = b;
        height = h;
    }

    double getDimension()   //  return volume/Qty.
    {
        float vol = length * breadth * height;
        return vol;
    }
}

As we can see that the myClass() constructor requires three parameters(l,b,h passed here). This means that every myClass object declaration must send three arguments to the constructor myClass().

The following statement, for example, is currently incorrect:

myClass class_obj = new myClass();

Since myClass() requires three arguments so it will be an error to call it without them. Now, Let's say we just needed a myClass object(class_obj ) with no initial dimensions, or we just wanted to initialize a cube by supplying a single value for all three dimensions. From the above implementation of myClass class, these options are currently not available to us.

As a result, constructor overloading can be used to handle difficulties like different ways of initializing an object.

Now, let us see the implementation of Constructor Overloading with a working example given below.

Recommended topic Iteration Statements in Java

Example of Constructor Overloading

In this example, We will be printing strings that will be returned from parameterized construction calls showing us the importance of Constructor Overloading.

Implementation  

  • Java

Java

public class myClass {
   private String str_txt;
   public myClass(){
      str_txt = "Welcome Ninjas To";
   }
   public myClass(String str_txt){
      this.str_txt = str_txt;
   }
public myClass(String str_txt, Int str_len){
      this.str_txt = str_txt;
   }
public myClass(String str_txt, Int str_len, Char buffer_char){
      this.str_txt = str_txt;
   }

   public String getmyClass(){ // getter for str_txt
      return str_txt ;
   }

   public void setmyClass(String str_txt){ // setter for str_txt
      this.str_txt = str_txt;
   }

   public static void main(String[] args) {
      myClass myClassObject1 = new myClass();
      System.out.println(myClassObject1.getmyClass());
 
      myClass myClassObject2 = new myClass("Code Studio Blog");
      System.out.println(myClassObject2.getmyClass()); 
   }
}
You can also try this code with Online Java Compiler
Run Code

In this example, the compiler first entered the main() method and the myClassObject1 object is invoked for myClass() class thereby redirecting us to myClass(). Then String str_txt is given a string("Welcome Ninjas To"), and we reach the constructor of myClass with a single parameter, Finally string is printed using getmyClass() getter. Similarly, myClassObject2 is invoked str_txt is passed with string("Code Studio Blog"), and the rest of the statements got executed, and the string gets printed.

Output:

Welcome Ninjas To
Code Studio Blog

Important considerations to keep in mind when performing Constructor Overloading are:

  • The first statement of a constructor in Java must be a constructor call.
  • Java prohibits the use of recursive constructors.
  • In Java, every class has a default constructor. Default overloaded constructor Java for class myClass is myClass(). If you don't give this constructor, the compiler will generate one for you and set the variables to their default values. As seen in Example, you can override the default constructor and set variables to your own values.
  • But suppose you specify a parametrized constructor like myClass(String str_txt) and want to use the default constructor Java myClass(). In that case, it is mandatory for us to specify it.
  • In other words, If your Java overloaded constructor is overridden and you wish to use the default constructor, you must provide it.

Use of this() in Constructor Overloading

In Java, this() is used within a constructor to call another constructor in the same class, a feature called constructor chaining. This enables code reuse by centralizing initialization logic in one constructor and simplifying the process of object creation.

Here are key scenarios where this() is beneficial:

  • Constructor Chaining: When a class has multiple constructors, this() helps delegate the task of object initialization to another constructor within the same class, reducing duplication.
     
  • Simplifying Initialization: By reusing constructors, it avoids the need to repeatedly write similar initialization code, improving maintainability and clarity.
     

Using this() effectively streamlines object creation, ensuring better code organization and reducing redundancy in Java development.

Example

public class Car {
    String model;
    int year;
    String color;

    // Constructor with three parameters
    public Car(String model, int year, String color) {
        this.model = model;
        this.year = year;
        this.color = color;
    }

    // Constructor with two parameters, calling the three-parameter constructor
    public Car(String model, int year) {
        this(model, year, "Unknown"); // Reuse the three-parameter constructor
    }

    // Default constructor, calling the two-parameter constructor
    public Car() {
        this("Default Model", 2020); // Reuse the two-parameter constructor
    }
}

In this example:

  • The three-parameter constructor initializes all fields.
  • The two-parameter constructor reuses the three-parameter constructor by providing a default value for color.
  • The default constructor reuses the two-parameter constructor by providing default values for model and year.

Benefits of Constructor Overloading in Java

  • Flexibility: Allows for various ways to initialize objects depending on the available data.
  • Code Reusability: Enables reuse of constructor logic, reducing code duplication.
  • Enhanced Readability: Simplifies code by providing multiple constructors for different initialization scenarios.
  • Default Values: Facilitates the provision of default values for certain parameters while allowing specific initialization.
  • Improved Maintainability: Makes code easier to maintain by clearly separating different initialization options.

Points to Remember While Doing Constructor Overloading

  • Unique Parameter Lists: Ensure that each overloaded constructor has a different number or type of parameters to avoid ambiguity.
  • Avoid Infinite Recursion: Be cautious with constructor chaining to prevent infinite recursion between constructors.
  • Initialization Order: Understand the order of constructor execution, especially when using this() for chaining.
  • No Return Type: Constructors do not have a return type, not even void.
  • Overloading vs. Overriding: Distinguish between constructor overloading (same method name, different parameters) and method overriding (same method name, same parameters but in a subclass).

Difference Between Constructor Overloading and Method Overloading in Java

ParametersConstructor OverloadingMethod Overloading
PurposeAllows multiple constructors with different parameters to initialize objects.Allows multiple methods with different parameters to perform various tasks.
NameConstructors have the same name as the class.Methods can have any name, as long as they are different from other methods.
Return TypeConstructors do not have a return type.Methods must have a return type (or void if no value is returned).
UsageUsed to initialize objects with different sets of data.Used to define multiple ways to perform similar operations.
InheritanceConstructors are not inherited by subclasses but can be called using super().Overloaded methods can be inherited and overridden in subclasses.
Constructor ChainingConstructors can call other constructors in the same class using this().Methods can call other methods, including overloaded versions, within the class.

Know about Single Inheritance in Java in detail.

Frequently Asked Questions

What is constructor overloading?

Constructor overloading in C++ or Java is defining multiple constructors in a class with different parameters, allowing objects to be initialized in various ways.

What is overriding vs overloading constructor?

Constructor overloading involves defining multiple constructors with different parameters, while constructor overriding doesn't apply as constructors cannot be overridden in subclasses.

 What is constructor overriding in Java?

Constructor overriding is not possible in Java because constructors are not inherited, and therefore, they cannot be overridden like methods.

What is the constructor and destructor?

A constructor is a special function that initializes objects when a class is instantiated, while a destructor is used to clean up resources when an object is destroyed.

Conclusion

In this article, we learned about Constructor Overloading and its implementation. Constructor overloading in Java is a powerful feature that enhances flexibility and code readability by allowing multiple constructors with different parameter lists within the same class. This capability enables developers to create objects in various ways, adapting to different initialization needs and improving code organization.

We hope this article has helped you enhance your knowledge of the Android Listeners, Handlers, and Registration. If you want to learn more, check out our Programming Fundamentals and Competitive Programming articles. Do upvote this article to help other ninjas grow.

Recommended Readings: 

Live masterclass