Constructor Overloading in Java

Constructor Overloading in Java

25 Sep 2024
Beginner
15.8K Views
12 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Constructor Overloading in Java: An Overview

Constructor Overloading in Javalets a Java class have multiple constructors with different parameter lists. It's a way to implement compile-time polymorphism. In this Java tutorial, we will learn more about this topicin detail. But, If you're a newbie to Java Language, try our Java Full Stack Developer Course.

Constructors in Java

Constructors in Java are special kinds of methods that are called when an object of a class is created. Constructors have no return value and they usually share the same name as the class. Constructors are used to assign initial values to the variables when an object is created.


   public class MyClass {
    int x;


    // Constructor
    public MyClass() {
        x = 0;
    }


    // Method to display the value of x
    public void display() {
        System.out.println("Value of x: " + x);
    }


    public static void main(String[] args) {
        MyClass obj = new MyClass(); // Constructor called
        obj.display();
    }
}

    

Output

Value of x: 0

Read More - Advanced Java Interview Questions And Answers

Read More - Java Multithreading Interview Questions

What is Constructor Overloading in Java?

Just like methods are overloaded in Java, overloading of constructors is also possible. We can define multiple constructors within a class and each of them can have different types of parameters. With the help of constructor overloading, objects of the class can be created with different kinds of information, we want to add to it.

Why do we need Constructor Overloading in Java?

Constructor Overloading helps in creating multiple constructors within a class, each accepting different parameters. This can be useful in many ways such as,

  • it provides flexibility in object creation.
  • it enables you to initialize objects in different ways depending on the information available or needed at the time of creation.
  • it also helps in making the code more simple.

Its Syntax and Structure

Here is the basic syntax and structure of Constructor Overloading in Java:


   public class MyClass {
   
    // Constructor with no parameters
    public MyClass() {
        // Initialization code
    }


    // Constructor with one parameter
    public MyClass(int parameter) {
        // Initialization code using the provided parameter
    }


    // Constructor with multiple parameters
    public MyClass(int parameter1, String parameter2) {
        // Initialization code using the provided parameters
    }


    // Additional constructors as needed...
}

    

Here, ‘MyClass’ contains multiple constructors. Each constructor has a different parameter list, allowing objects of ‘MyClass’ to be initialized in different ways based on the arguments provided when the constructor is called. The constructors can then perform specific initialization tasks based on the parameters they receive.

Example of Constructor Overloading in the Java Compiler


    public class Employee {
    String name;
    int id;


    // Default constructor
    public Employee() {
        name = "Unknown";
        id = 0;
    }


    // Parameterized constructor
    public Employee(String empName, int empId) {
        name = empName;
        id = empId;
    }


    public void display() {
        System.out.println("Name: " + name + ", ID: " + id);
    }


    public static void main(String[] args) {
        Employee emp1 = new Employee(); // Default constructor
        Employee emp2 = new Employee("John", 101); // Parameterized constructor


        emp1.display();
        emp2.display(); 
    }
}
    

Output

Name: Unknown, ID: 0
Name: John, ID: 101 

Use of this() in Constructor Overloading

In Java, ‘this()’ is a keyword used inside a constructor to call another constructor from the same class. This is a useful keyword in constructor overloading as we have constructors so it gives the advantage of reusing code from one constructor to another constructor in the same class. Instead of writing the same code again and again, we can just use ‘this()’ to call another constructor with similar or additional parameters. It reduces redundancy making the code more efficient.

Example:


    public class Person {
    private String name;
    private int age;


    // Constructor with only name parameter
    public Person(String name) {
        this.name = name;
    }


    // Constructor with name and age parameters
    public Person(String name, int age) {
        // Calling the constructor with only name parameter using this()
        this(name);
        this.age = age;
    }


    public void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }


    public static void main(String[] args) {
        // Creating objects using different constructors
        Person person1 = new Person("Alice");
        Person person2 = new Person("Bob", 30);


        // Displaying details
        person1.displayDetails();
        person2.displayDetails();
    }
}    

Output

Name: Alice
Age: 0
Name: Bob
Age: 30 

Benefits of Constructor Overloading in Java

Constructor Overloading offers several benefits, some of its key advantages are as follows:

  • Flexibility-Constructor Overloading allows developers to create objects in different ways by providing multiple constructors with different parameter lists making the process of initializing objects more flexible.
  • Code Reusability- Insteadof duplicating code or creating similar constructors with minor variations, developers can overload existing constructors to accommodate new initialization requirements without redundancy.
  • Code Readability- While overloading constructors, developers can provide meaningful names to constructors and parameters that will convey the purpose and usage of each constructor effectively, enhancing the code readability and understanding.
  • Maintainability- With constructor overloading, developers can easily create new or modify existing constructors as they want to. It won't affect the main codebase in any way.
  • Enables Polymorphic Behavior- Constructor Overloading also contributes to the polymorphism in Java classes, enabling objects to exhibit different behaviors based on the parameters used to instantiate them.

Points to remember while doing Constructor Overloading

  1. Avoid Ambiguity- You must ensure that the parameter lists of overloaded constructors are unique so that during object instantiation, any kind of ambiguity is avoided.
  2. Follow Naming Conventions- You should use names that are meaningful while creating parameters and constructors to enhance code readability and its proper understanding.
  3. Keep Constructors concise- Note that constructors must focus on initializing the object state. Complex logic or huge processing must be avoided within constructors.

Difference between Constructor overloading and method overloading in Java

The difference between constructor overloading and method overloading in Java lies in their purpose and usage.

Constructor OverloadingMethod Overloading
It involves defining multiple constructors within a class, each with a different parameter list.It involves defining multiple methods within a class with the same name but different parameter lists.
Constructors help in initializing objects when they are created.Methods help in performing specific actions or tasks within a class.
They have the same name as the class and do not have a return type, not even ‘void’.They can have any anime except the class name and may have different return types or even no return type.
Constructor Overloading allows initialization of objects in various ways based on the parameters passed during instantiation.Method Overloading enables a single method name to perform different tasks based on the parameters passed to it.
Summary

So, we learned how Constructor overloading in Java is a feature that can help in many ways if understood and used properly. With the help of constructor overloading, Java developers can write more flexible, readable, and maintainable code. If you want more guidance on this topic, do consider our Java Full Stack Developer Training.

FAQs

Yes, constructors can be overloaded in Java by providing multiple constructors with different parameter lists. You can easily create objects in different ways, depending on the parameters passed during the instantiation of objects.

Constructor overloading refers to defining multiple constructors within a class with different parameter lists for creating different objects with various initializations. Whereas, there is no such thing as constructor overriding in Java because constructors cannot be overridden; only methods can.

In Java, a copy constructor overloading involves creating a special constructor within a class that copies the data of an existing object into a new object.

Yes, it is totally possible to call one constructor from another constructor in Java using the ‘this()’ keyword. This feature is commonly known as Constructor Chaining in Java.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this