Constructor Overloading in Java

Constructor Overloading in Java

12 Apr 2024
Beginner
1.18K Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Constructor Overloading in Java: An Overview

Constructor Overloading in Java lets 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 topic in detail. But, If you're a newbie to Java Language, try our Java Programming 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

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- Instead of 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 Online Course.

FAQs

Q1. Can Constructors be overloaded in Java?

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.

Q2. What is the difference between constructor overloading and constructor overriding?

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.

Q3. What is copy constructor overloading in Java?

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.

Q4. Is it possible to call one constructor from another constructor in Java?

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
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this