Card 01/ 09
All 9 cards
ConceptDifficulty: Beginner1 min
A Class Is a Description; an Object Is One of the Things It Describes
A shop has eleven thousand orders. Each one has a customer, a total and a status, and every one of them 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 is how you write the shape and the rules once.
class Order {
String customer;
double total;
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.
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.
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.