Card 03/ 09
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:
class Order {
String customer;
long totalPence;
String status;
Order(String customer, long totalPence) {
this.customer = customer;
this.totalPence = totalPence;
this.status = "open";
}
}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.
| 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 |
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.
← → move through sections and cards