Card 03/ 09

ConceptDifficulty: Beginner1 min

The Method That Runs Before the Object Exists

Making an order takes four lines: one new and three assignments. Forget the third assignment and you have an order with no total, which nothing prevents and nothing reports until something divides by it.

A constructor is the code that runs as part of new, before anybody gets the reference back. It is where an object is made valid.

java
class Order {
    String customer;
    double total;
    String status;

    Order(String customer, double total) {
        this.customer = customer;
        this.total = total;
        this.status = "open";
    }
}
java
Order a = new Order("Ada", 42.50);

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 will accept and never call.

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

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.