Constructor Overloading in Java
Constructor overloading is a technique where a class has more than one constructor, each with a different parameter list. It allows objects to be created in different ways depending on the arguments provided.
Example
class Student {
String name;
int age;
Student() {
this.name = "Unknown";
this.age = 0;
}
Student(String name) {
this.name = name;
this.age = 0;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Student s1 = new Student();
Student s2 = new Student("Karan");
Student s3 = new Student("Meera", 23);
Rules for Constructor Overloading
- Each constructor must differ in the number, type, or order of parameters
- Constructors share the class name, so overloading relies entirely on parameter lists
- One constructor can call another using
this()to avoid repeating initialization logic
Why Use Constructor Overloading?
- Gives users of the class flexibility to create objects with different amounts of initial information
- Supports default values when certain fields aren't provided
- Improves code usability without duplicating the entire class logic
Constructor overloading is a form of compile-time polymorphism, just like method overloading — the compiler picks the right constructor based on the arguments passed.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.