Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Constructor Overloading
2.1.
Need for Constructor Overloading
3.
Example
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024

Constructor Overloading In Java

Author Akshit Pant
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Constructor overloading is the concept of having many constructors, each with a different set of parameters, each doing a different task.

Before jumping directly on how Constructor Overloading is used, first knowing the basic knowledge of Constructors in Java is strongly recommended.

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

Also read, Swap Function in Java

Constructor Overloading

Constructor overloading in Java is a technique that allows a class to have as many constructors as it wants, each with a different argument list. The number of parameters in the list and their type is used by the compiler to distinguish these constructors.

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

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

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).

Code:

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 JavaDuck Number in Java and Hashcode Method in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example

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

Code:

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());  
    }
 }  

 

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.

    You can also read about the Multiple Inheritance in Java.

Know about Single Inheritance in Java in detail.

Frequently Asked Questions

  1. What's the difference between overloading constructors and chaining constructors?
    Constructor overloading allows a class to have many constructors with the same name but differing only in terms of the number or type of parameters. With respect to the current object, constructor chaining is the process of calling one constructor from another constructor.
     
  2. In Java, what is a constructor?
    In Java, a constructor is equivalent to a method that is called when a class object is formed. A constructor, unlike Java methods, has the same name as the class and does not have a return type.
     
  3. In Java, what is overloading?
    In Java, two or more methods can have the same type of name if they have different parameters (different numbers of parameters or different types of parameters, or both). These methods are called overloaded methods, and this overloading feature is called method overloading. 
     
  4. In Java, how many different types of constructors are there?
    Constructors in Java are grouped into three categories: Constructors with no arguments, Constructors with parameters, and Constructors by default.

Conclusion

In this article, we learned about Constructor Overloading and its implementation. We also infer from this article why Constructor Overloading is needed.

You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.

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: 

Previous article
Getter and Setter in Java
Next article
Order of execution of constructors in java inheritance
Live masterclass