Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Constructor Overloading in Java

Last Updated on July 20, 2023 by Mayank Dham

Constructor overloading in Java allows developers to define multiple constructors within a class, each with a distinct set of parameters. This powerful feature provides flexibility in object creation, enabling the selection of appropriate constructors based on different scenarios and input variations.
In the world of Java programming, constructors play a vital role in creating and initializing objects. They provide a mechanism to set the initial state of an object by defining a special method with the same name as the class. While a class can have multiple constructors, each with different parameters, the concept of constructor overloading comes into play. Let’s see what is constructor overloading in Java example and we will also look into the difference between method overloading and constructor overloading in Java.

What is Constructor Overloading in Java?

Constructor overloading in Java refers to the practice of defining multiple constructors within a class, each with a different set of parameters. It allows the class to have multiple ways of creating objects with varying initializations. By providing different constructors, Java enables developers to create objects using different combinations of input values, providing flexibility and customization in object creation.

Constructor overloading is based on the concept of polymorphism, where different constructors with the same name but different parameter lists can be called based on the arguments passed during object creation. This enables the class to accommodate different scenarios and simplify object instantiation.

Constructor Overloading in Java Example

Here are some examples of constructor overloading in Java with code and explanation:

Example 1 of Constructor Overloading in Java
Creating a class with multiple constructors that take different parameters

Code:

class Person {
    private String name;
    private int age;
   
    // Default constructor
    public Person() {
        name = "";
        age = 0;
    }
   
    // Constructor that takes a name parameter
    public Person(String name) {
        this.name = name;
        age = 0;
    }
   
    // Constructor that takes both name and age parameters
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }


    public String toString(){
        return name + " " + age;
    }
}


class PrepBytes{
    public static void main(String args[]){
        Person p1 = new Person();
        Person p2 = new Person("PrepBuddy");
        Person p3 = new Person("PrepBuddy", 18);


        System.out.println(p1.toString());
        System.out.println(p2.toString());
        System.out.println(p3.toString());
    }
}

Output:

0
PrepBuddy 0
PrepBuddy 18

Explanation:
In this example, we have created a Person class with three constructors. The first constructor is a default constructor that initializes the name and age fields to empty strings and zero, respectively. The second constructor takes a name parameter and initializes the name field to the value of the parameter while leaving the age field at zero. The third constructor takes both a name and age parameter and initializes both fields to the corresponding values. We have also overridden the toString method to show the elements of the objects on the console screen.

In the main method, we have initialized three objects of class Person by providing the different numbers of parameters. Then we utilized the toString Function for showing the output on the screen.

Example 2 of Constructor Overloading in Java
Creating a class with a constructor that calls another constructor using the "this" keyword

Code:

class Rectangle {
    public int width;
    public int height;
   
    // Constructor that takes width and height parameters
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
   
    // Constructor that takes a width parameter and sets the height to the same value
    public Rectangle(int width) {
        this(width, width);
    }
}


class PrepBytes{
    public static void main(String args[]){
        Rectangle rec1 = new Rectangle(5);
        System.out.println("Height of Rectangle is " + rec1.height);
        System.out.println("Width of Rectangle is " + rec1.width);
    }
}

Output:

Height of Rectangle is 5
Width of Rectangle is 5

Explanation:
In this example, we have created a Rectangle class with two constructors. The first constructor takes width and height parameters and initializes the corresponding fields to the values of the parameters. The second constructor takes a width parameter and calls the first constructor using the "this" keyword, passing in the width parameter for both the width and height parameters. This allows the second constructor to reuse the logic of the first constructor while providing a simpler interface for creating squares.

Benefits of Constructor Overloading in Java

Constructor overloading in Java provides several benefits to Java developers. Some of the benefits are listed below:

  • Allows for object initialization with different initial states: By defining multiple constructors with different parameter lists, developers can create objects with different initial states without having to create separate classes.
  • Increases code readability: Constructor overloading allows developers to provide descriptive names for constructors, which can increase code readability and make the code easier to understand.
  • Reduces code duplication: By providing multiple constructors with different parameter lists, developers can avoid duplicating code in different parts of the class.
  • Simplifies object creation: By providing multiple constructors with different parameter lists, developers can simplify the process of creating objects by providing different ways to initialize them.

Let’s look into the difference between method overloading and constructor overloading in Java.

Method Overloading vs Constructor Overloading in Java

Here are the differences between Method Overloading and Constructor Overloading in Java.

Constructor Overloading Method Overloading
Constructors are special methods in Java that are called when an object is created. Methods are normal functions in Java that can be called on an object or class.
Constructor overloading allows a class to have multiple constructors with different parameter lists. Method overloading allows a class to have multiple methods with the same name but different parameter lists.
Constructors are always called when an object is created, and the appropriate constructor is automatically selected based on the arguments used to create the object. Methods are called explicitly by name and can be passed different arguments at each call.
The purpose of constructor overloading is to provide different ways to initialize an object of a class. The purpose of method overloading is to provide different ways to perform a specific action in a class.
Constructors do not have a return type. Methods can have a return type, which can be different for each overloaded method.

Conclusion
Constructor overloading in Java is a powerful language feature that allows developers to create multiple constructors within a class, each with a distinct set of parameters. It provides flexibility and customization in object creation by accommodating different input variations. Throughout this article, we have explored the significance of constructor overloading and its benefits in Java programming.
It is important to note the key distinction between method overloading and constructor overloading. While both involve defining multiple versions of a function with the same name, method overloading applies to regular methods within a class, while constructor overloading specifically applies to constructors. Method overloading enables the execution of different functionalities with the same method name, while constructor overloading provides different ways to initialize objects.

Frequently Asked Questions (FAQs) on Constructor Overloading in Java

Here are Frequently Asked Questions on Constructor Overloading in Java.

Q1: Can constructor overloading be used in inheritance?
A: Yes, constructor overloading can be used in inheritance. Subclasses can have their own set of constructors, including overloaded constructors, in addition to inheriting constructors from the superclass. The subclass constructors can call the superclass constructors explicitly using the "super" keyword or invoke overloaded constructors within the subclass itself. This allows for customization and flexibility in object creation within the inheritance hierarchy.

Q2: Can we overload constructors with the same number and types of parameters in Java?
A: No, constructors must have different parameter lists in order to be considered overloaded. Java distinguishes overloaded constructors based on the number, order, or types of parameters. If two constructors have the same number and types of parameters, the compiler will generate an error as they would be considered duplicate declarations.

Q3: Can a class have both overloaded constructors and a default constructor?
A: Yes, a class can have both overloaded constructors (constructors with parameters) and a default constructor (constructor without parameters). The default constructor is automatically provided by Java if no other constructors are explicitly defined. Overloaded constructors provide additional options for object initialization, while the default constructor serves as a fallback option or when no specific initialization is required.

Q4: How is constructor overloading resolved at compile-time?
A: Constructor overloading in Java is resolved at compile-time based on the arguments provided during object creation. The compiler selects the appropriate constructor based on the compatibility of the arguments with the available constructor signatures. If an exact match is found, that constructor is invoked. If not, the compiler looks for the closest possible match based on widening conversions, autoboxing, or varargs.

Leave a Reply

Your email address will not be published. Required fields are marked *