Card 05/ 09

GotchaDifficulty: Intermediate1 min

Why Adding a Constructor Broke Every new Order()

You add a constructor that takes a customer and a total. Nothing else changes, and forty call sites you did not touch stop compiling.

text
Checkout.java:18: error: constructor Order in class Order cannot be applied to given types;
        Order draft = new Order();
                      ^
  required: String,double
  found:    no arguments
  reason: actual and formal argument lists differ in length

A class with no constructor written in it gets one for free: a no-argument constructor that does nothing. It is not in the source, which is why it is easy to forget it was ever there.

The moment you write any constructor, the free one stops being supplied. 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.