Card 03/ 09
All 9 cards
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.
class Order {
String customer;
double total;
String status;
Order(String customer, double total) {
this.customer = customer;
this.total = total;
this.status = "open";
}
}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.
| Compared on | Constructor | Method |
|---|---|---|
| Runs | As part of new, once | Whenever something calls it |
| Return type | None is written | Required, even if void |
| Can be called by name | No | Yes |
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.