Constructor
Source: Dev.to
Constructor
- The constructor name must be the same as the class name.
- A constructor is a special method used to initialize instance variables when an object is created.
- When an object is instantiated, the constructor runs automatically; it cannot be called manually.
- In Java, constructors are defined using the class name (no return type).
Example
public class Bank {
int accountNo;
String name;
int balance;
Bank(int accountNo, String name, int balance) {
this.accountNo = accountNo;
this.name = name;
this.balance = balance;
}
public static void main(String[] args) {
Bank accHolder1 = new Bank(101, "kumar", 1000);
System.out.println(accHolder1.accountNo); // 101
Bank accHolder2 = new Bank(102, "hari", 1000);
System.out.println(accHolder2.accountNo); // 102
}
}
Purpose of Constructor
- The
thiskeyword refers to the current object. - Inside a constructor,
thisis used to assign values to instance variables, distinguishing them from parameters or local variables.
Constructor Overloading
Constructor overloading means defining multiple constructors with different parameter lists.
public class Payilagam {
String name;
String email;
String password;
// Constructor with name, email, and password
Payilagam(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
// Constructor with only email and password
Payilagam(String email, String password) {
this.email = email;
this.password = password;
}
public static void main(String[] args) {
Payilagam user2 = new Payilagam("abc.com", "kumar@123");
System.out.println(user2);
}
}