DEV Community

Dinesh G
Dinesh G

Posted on

Constructor overloading in java

What is Constructor Overloading?

  • Constructor overloading in Java means having multiple constructors in the same class, each with a different parameter list.
  • The constructors are differentiated by the number and types of their parameters.
  • This allows you to create objects with varying initial states based on what data is available when the object is instantiated.

Why Use Constructor Overloading?

Constructor overloading is useful for several reasons:

  • Flexibility: It provides multiple ways to create objects with different initial values.
  • Convenience: Users of your class can choose which constructor to call based on the information they have.
  • Code Reusability: It allows for a default setup while still enabling customization.

Example of Constructor Overloading

Let’s consider a simple example of an Employee class to see how constructor overloading works

public class Employee {
    private String name;
    private int id;
    private double salary;

    // Constructor 1: No parameters
    public Employee() {
        this.name = "Unknown";
        this.id = 0;
        this.salary = 0.0;
    }

    // Constructor 2: One parameter (name)
    public Employee(String name) {
        this.name = name;
        this.id = 0;
        this.salary = 0.0;
    }

    // Constructor 3: Two parameters (name and id)
    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
        this.salary = 0.0;
    }

    // Constructor 4: Three parameters (name, id, and salary)
    public Employee(String name, int id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    public void displayInfo() {
        System.out.println("Name: " + name + ", ID: " + id + ", Salary: " + salary);
    }
}
Enter fullscreen mode Exit fullscreen mode

How Does It Work?

In the Employee class above:

  • Constructor 1 is a no-argument constructor that sets default values for the name, id, and salary.
  • Constructor 2 allows you to set the name, with id and salary defaulting to 0.
  • Constructor 3 lets you set both name and id, while salary still defaults to 0.
  • Constructor 4 gives you the flexibility to set all three fields: name, id, and salary.

Top comments (0)