Card 01/ 09

ConceptDifficulty: Beginner1 min

Classes and Objects: A Description and Its Instances

Eleven thousand orders, one set of rules for cancelling them, written once.

A class is a description: the data each object of that kind holds, in fields, and what each can do, in methods. An object, or instance, is one thing made from that description with new, holding its own values for every field. One class can describe any number of objects.

A shop has eleven thousand orders. Each has a customer, a total and a status, and every one works the same way: you can cancel any of them, and the rule for cancelling is the same rule. Writing eleven thousand sets of variables is not an option, and neither is writing the cancelling rule once per order. A class writes the shape and the rules once:

java
class Order {
    String customer;
    long totalPence;
    String status = "open";

    void cancel() {
        status = "cancelled";
    }
}

Nothing in that listing is an order. It is a description of what any order has, three fields, and what any order can do, one method. Running the program creates none of them. Creating one takes new:

java
Order first = new Order();
first.customer = "Ada";

new Order() is what makes an actual order: its own customer, its own total, its own status. The variable first holds the address of that one object, and calling first.cancel() changes that one object's status and no other.

The total is held as a whole number of pence, totalPence, because a double cannot hold amounts like 19.99 exactly.

So one class and eleven thousand objects means one copy of the rules and eleven thousand sets of values, which is what makes it possible to change how cancelling works in one place.