Constructors
How to build objects that are valid from their very first instruction, using chained constructors.
Open this lesson in the learning hubKey points
- A constructor runs once, at creation. Its job is to leave the object in a valid state, or refuse to build it.
- Same name as the class, no return type. Write none and Java gives you an empty no-arg constructor for free.
- Write any constructor and that free one disappears. Add it back yourself if callers still need it.
- Overload for convenience, then chain with
this(...)so the real work lives in exactly one constructor. - Validate arguments here, not later. An
IllegalArgumentExceptionnow beats a half-built object roaming loose. this.x = xsimply distinguishes the field from the parameter. Nothing more magical than that.
Example
public class Main {
static class Account {
private final String owner;
private double balance;
Account(String owner, double balance) {
if (owner == null || owner.isBlank()) {
throw new IllegalArgumentException("owner is required");
}
this.owner = owner; // 'this' = the object being built
this.balance = balance;
}
Account(String owner) {
this(owner, 0.0); // delegate; must be the first statement
}
@Override public String toString() {
return owner + ": " + balance;
}
}
public static void main(String[] args) {
System.out.println(new Account("Ada", 250.0));
System.out.println(new Account("Linus"));
try {
new Account(" ");
} catch (IllegalArgumentException e) {
System.out.println("rejected at birth: " + e.getMessage());
}
}
}
A constructor guards the door: no object should ever exist in an invalid state.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.