Card 03/ 09

ConceptDifficulty: Beginner1 min

Java Constructors: Making an Object Valid From the Start

Forget one of three assignments and you have an order with no total, which nothing reports.

A constructor is code that runs as part of new, before anyone receives the new object. It is named exactly as the class is and declares no return type, and it is where an object is given every value it needs to be valid.

Making an order field by field, setting each of its variables in turn, takes four lines: one new and three assignments. Forget one of the assignments and you have an order with no total, which nothing prevents and nothing reports. A constructor takes the required values as parameters, so a caller cannot make an order without them:

java
class Order {
    String customer;
    long totalPence;
    String status;

    Order(String customer, long totalPence) {
        this.customer = customer;
        this.totalPence = totalPence;
        this.status = "open";
    }
}
java
Order a = new Order("Ada", 4250);

Two things make it a constructor rather than a method. It is named exactly as the class is, and it declares no return type at all, not even void. Write void Order(...) and you have an ordinary method with a confusing name, which the compiler accepts and new never calls.

What a constructor does that an ordinary method cannot
Compared onConstructorMethod
RunsAs part of new, onceWhenever something calls it
Return typeNone is writtenRequired, even if void
Can be called by nameNoYes

The constructor can also refuse bad values, by throwing an exception when a total is negative, for example, so an invalid order never exists at all.

So a constructor is the only place that can guarantee something about every object of a class. Anything required for an order to make sense belongs in its parameters, because a caller then cannot make one without supplying it.