Card 05/ 09
The Default Constructor Disappears When You Write One
You add one constructor, and forty call sites you did not touch stop compiling.
A class with no constructor written in it gets a default constructor from the compiler: one that takes no arguments and does nothing. Writing any constructor yourself stops the compiler supplying it, so every new Order() with empty brackets stops compiling.
You add a constructor that takes a customer and a total. Nothing else changes, and forty call sites you did not touch fail:
Checkout.java:18: error: constructor Order in class Order cannot be applied to given types;
Order draft = new Order();
^
required: String,long
found: no arguments
reason: actual and formal argument lists differ in lengthThe default constructor is not in the source, which is why it is easy to forget it was ever there. The compiler's rule is not "add one if there is no no-argument constructor"; it is "add one if there are no constructors at all".
Decide which it should be, rather than restoring the old one by reflex. If an order genuinely cannot exist without a customer, the forty call sites are telling you where the missing customers are. If it can, write Order() { } explicitly, so the next reader can see it was a decision.
← → move through sections and cards