In this section, we will learn what the constructor overloading is and how to use it in Java.
Note: We’re assuming you’re familiar with the constructors in Java. If don’t please check the referred section first.
What is constructor overloading?
In Java, depending on the need of a class, we’re able to define as many constructors as we need for that particular class (including an empty constructor) and this is called constructor overloading.
Example: using constructor overloading in Java
public class Employee {
private String name;
private String lastName;
private int id;
public Employee(){}
public Employee(int id){
this.id = id;
}
public Employee(String name, String lastName){
this.name = name;
this.lastName = lastName;
}
public Employee(int id, String name, String lastName){
this.id = id;
this.name = name;
this.lastName = lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In the `Employee` class we’ve added 4 constructors as follows:
public Employee(){}
public Employee(int id){
this.id = id;
}
public Employee(String name, String lastName){
this.name = name;
this.lastName = lastName;
}
public Employee(int id, String name, String lastName){
this.id = id;
this.name = name;
this.lastName = lastName;
}
How Does Constructor Overloading Work in Java?
The first constructor is an empty one (no-parameter and nobody).
The second one takes only one argument, and that is the value for the `id` variable.
The third one takes two arguments and those are assigned to the `name` and the `lastName` member variables.
The fourth one takes 4 arguments and these arguments are assigned to the 4 member variables of the object as the body of this constructor shows.
Note: When we want to create an object from a class that has multiple constructors, we have the option to choose any of those constructors that fit our needs.
Example:
public class Simple {
public static void main(String[] args) {
Employee emp = new Employee(); //public Employee();
Employee emp1 = new Employee(10); //public Employee(int id);
Employee emp2 = new Employee("John","Doe"); //public Employee(String name, String lastName);
Employee emp3 = new Employee(10, "John","Doe"); //public Employee (int id, String name, String lastName);
}
}
In this example, the `emp` instance is created from the empty constructor `public Employee()`.
The `emp1` is created via calling the ` public Employee(int id)` constructor.
The `emp2` is created via calling the ` public Employee(String name, String lastName)` constructor.
And the `emp3` is created via the call to the` public Employee (int id, String name, String lastName)` constructor.