Card 04/ 09

ExampleDifficulty: Intermediate1 min

Two Constructors for One Order, and Which One Runs

Most orders have a delivery note and some do not. Rather than making every caller pass an empty string, the class offers two ways in.

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

    Order(String customer, double total, String note) {
        this.customer = customer;
        this.total = total;
        this.note = note;
    }

    Order(String customer, double total) {
        this(customer, total, "");
    }
}
java
Order a = new Order("Ada", 42.50);
Order b = new Order("Grace", 19.99, "leave with neighbour");

The compiler picks by the argument list, exactly as it does for overloaded methods: two arguments match the second constructor, three match the first. The types and the count decide, and nothing else can.

Line 13 is the part worth copying. this(...) calls another constructor of the same class, and it must be the first statement in the body. It means the real work stays in one constructor and the others are short paths into it, so a rule added later is added once.