---Advertisement---

Constructor Overloading in Java

By Shiva

Published On:

---Advertisement---

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.

  • 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.
java

class 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();
}
}
  • 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. 🚀

---Advertisement---

Leave a Comment