Constructor Overloading in Java
What is Constructor Overloading in Java?
Constructor overloading in Java is a technique where a class can have multiple constructors with different parameter lists. The compiler differentiates these constructors based on the number and type of parameters.
Why is Constructor Overloading Important?
- Flexibility: Allows object creation with different initialization options.
- Code Reusability: Enables calling one constructor from another using
this()
. - Better Readability: Improves clarity by offering different ways to instantiate objects.
- Default and Custom Initialization: Supports both automatic and user-defined initialization.
Example of Constructor Overloading in Java
javaclass Account {
int accountNumber;
double balance;
// Default Constructor
Account() {
this.accountNumber = 0;
this.balance = 0.0;
System.out.println("Default Constructor Called");
}
// Constructor with one parameter
Account(int accNo) {
this.accountNumber = accNo;
this.balance = 0.0;
System.out.println("Constructor with Account Number Called");
}
// Constructor with two parameters
Account(int accNo, double bal) {
this.accountNumber = accNo;
this.balance = bal;
System.out.println("Constructor with Account Number and Balance Called");
}
void display() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
public static void main(String[] args) {
Account acc1 = new Account();
Account acc2 = new Account(1001);
Account acc3 = new Account(1002, 5000.75);
acc1.display();
acc2.display();
acc3.display();
}
}
Keywords For Construction Overloading in Java:-
- Java Constructor Overloading
- Java OOP Concepts
- Parameterized Constructor in Java
- Multiple Constructors in Java
- Object-Oriented Programming in Java
- Java Interview Questions on Constructors
By understanding constructor overloading, developers can create Java programs that are more flexible, efficient, and maintainable.