Constructor Overloading in Java with Examples
Constructor Overloading in Java
Constructor overloading is a feature in Java where multiple constructors are created within the same class, all having the same class name but different parameter lists.It allows objects to be initialized in different ways, depending on the values provided during object creation.
✅ Definition
- Constructor overloading occurs when:
- Constructors have the same name as the class
- But have different parameters (number, type, or order)
- Java decides which constructor to call based on the arguments passed during object creation.
🌍 Real-Life Example
- Mobile Phone Purchase
- Buy phone with only model name
- Buy phone with model + price
- Buy phone with model + price + color
- Each purchase method represents a different constructor.
🔹 Ways to Perform Constructor Overloading
Constructor overloading can be achieved in three ways:
1. Changing the Data Type of Parameters
class Sample {Sample(int a) {
System.out.println("Integer Constructor");
}
Sample(double a) {
System.out.println("Double Constructor");
}
}
2. Changing the Number of Parameters
class Student {Student(int id) {
System.out.println("ID Constructor");
}
Student(int id, String name) {
System.out.println("ID and Name Constructor");
}
}
3. Changing the Order of Parameters
class Employee {
Employee(int id, String name) {
System.out.println("ID then Name");
}
Employee(String name, int id) {
System.out.println("Name then ID");
}
}
🧠 How Java Selects the Constructor
- Java selects the constructor based on:
- Number of arguments
- Data types of arguments
- Order of arguments
📌 Advantages of Constructor Overloading
- Allows flexible object initialization
- Improves code readability
- Supports multiple ways to create objects
- Reduces the need for multiple classes
Comments
Post a Comment