What is a constructor?
Solution and explanation
What it is
A constructor is a special block of code that runs automatically when an object is created with new. Its job is to initialise the new object so it starts in a valid state.
Rules that make it different from a method
- Its name is exactly the class name.
- It has no return type, not even
void. - It is called once per object, by
new(or bythis()/super()from another constructor). - It cannot be
static,finalorabstract. - It can have any access modifier: public, protected, package-private or private.
public class Account {
private final String accountNo;
private final String holder;
private double balance;
public Account(String accountNo, String holder, double openingDeposit) { // constructor
if (openingDeposit < 1000) throw new IllegalArgumentException("Minimum opening deposit is ₹1000");
this.accountNo = accountNo;
this.holder = holder;
this.balance = openingDeposit;
}
}
Account acc = new Account("SB1001", "Kiran", 5000);
What happens on new
- Memory is allocated and fields get default values.
- The constructor is called; its first line calls the parent constructor (
super()). - Field initializers and instance blocks run.
- The rest of the constructor body runs.
- The reference to the fully initialised object is returned.
Note: if a method has the same name as the class but a return type (public void Account() {}), it is an ordinary method, not a constructor. The compiler allows it, which makes it a classic trick question.
