Constructor overloading in Java allows a class to have multiple constructors with different parameter lists. This helps create objects in different ways depending on the data available at the time of object creation.
A constructor has the same name as the class and no return type. Overloading occurs when constructors differ by parameters.
// Class demonstrating constructor overloading
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "Unknown";
}
// Parameterized constructor with one parameter
Student(int i) {
id = i;
name = "Not Assigned";
}
// Parameterized constructor with two parameters
Student(int i, String n) {
id = i;
name = n;
}
}
// Main class to test constructor overloading
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student(101);
Student s3 = new Student(102, "Amit");
System.out.println(s1.id + " " + s1.name);
System.out.println(s2.id + " " + s2.name);
System.out.println(s3.id + " " + s3.name);
}
}
Simulate creating a Car object. Enter values below and click a constructor button to see how overloading logic selects the initializer.
The program creates three objects using different constructors. Each constructor initializes the object differently based on the parameters passed.
Book with overloaded constructors