What is a constructor, and what does it guarantee about a newly created object?
A constructor is the method that runs when an object is created. Its job is to make sure that the object is fully set up and valid before anybody can use it.
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.owner()); // Ada
System.out.println(b.balance()); // 0.0
}
}
And what does it guarantee about a newly created object? Everything about the state. After the constructor returns, the object has all its fields set to something sensible, and no other code has seen the object yet, so it cannot be in a half-built state.
public class Account {
private final String owner;
private double balance;
public Account(String owner) {
this(owner, 0.0);
}
public Account(String owner, double startingBalance) {
if (owner == null || owner.isBlank()) {
throw new IllegalArgumentException("owner is required");
}
if (startingBalance < 0) {
throw new IllegalArgumentException("balance cannot be negative");
}
this.owner = owner;
this.balance = startingBalance;
}
public String owner() {
return owner;
}
public double balance() {
return balance;
}
}
And there are three things that make this guarantee real.
The first one is that the fields are final where they can be. A final field cannot be changed after the constructor gives it a value, so the object cannot be edited behind your back later. That is why owner is final above and balance is not, because the balance does change later.
The second one is that the constructor checks its arguments. If the starting balance is negative then the object is never created, so there is no invalid account in the program at all. That is stronger than creating it and then fixing it later.
The third one is that every field is assigned. In Java the compiler checks this, and it gives you a compile error if a final field might not be set. So you cannot forget one.
the guarantee how it is made
---------------------------- --------------------------------
no field is left unset the compiler checks it
no field is left invalid the constructor throws
nothing has seen it yet the object is made in one step
So the rule to remember is this. A constructor turns an allocated block of memory into a valid object, and it is the last chance to reject bad values.
The next two questions in this topic are about the constructor overloading and about the super call.