What is a constructor, and what does it guarantee about a newly created object?
A constructor is a special method whose name matches the class name and whose job is to bring a freshly allocated object into a usable state. It has no return type, not even void, because it does not return anything: the runtime does that for you. Its body is the first code that ever executes for that object.
public class Main {
public static void main(String[] args) {
Account a = new Account("Ada", 100.0);
Account b = new Account("Grace");
System.out.println(a);
System.out.println(b);
}
}
class Account {
private final String owner;
private double balance;
Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
Account(String owner) {
this(owner, 0.0);
}
void deposit(double amount) { balance += amount; }
public String toString() { return owner + " " + balance; }
}What it guarantees is that the object is valid before any other code can see it. Because the constructor runs before the reference escapes to the caller, there is no window in which a half-built object exists. Fields that must be set can be final, so the compiler enforces that every path through the constructor sets them. The second constructor delegates to the first through this, so there is one place where the rules are written rather than two.
Two design points are worth mentioning in an interview. First, keep constructors small and side-effect free; a constructor that sends an email or writes to a database makes object creation unpredictable and hard to test. Second, prefer making invalid states unrepresentable by validating in the constructor, rather than by hoping callers remember to validate afterwards.