Card 04/ 09

ExampleDifficulty: Intermediate1 min

Constructor Overloading Example: Two Ways to Create an Order

Some orders have a delivery note and some do not, and neither caller should pass an empty string.

A class can declare several constructors with different parameter lists, and new picks one by the arguments it is given. Most orders have no delivery note and some do, so the class offers two ways in:

java
class Order {
    String customer;
    long totalPence;
    String note;

    Order(String customer, long totalPence, String note) {
        this.customer = customer;
        this.totalPence = totalPence;
        this.note = note;
    }

    Order(String customer, long totalPence) {
        this(customer, totalPence, "");
    }
}
java
Order a = new Order("Ada", 4250);
Order b = new Order("Grace", 1999, "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.