Card 07/ 09
All 9 cards
ComparisonDifficulty: Intermediate1 min
static Belongs to the Class; Everything Else Belongs to the Object
Every order needs a reference number, and the numbers have to be unique across all orders. Putting the counter on each order gives every order its own counter, all of them starting at one.
class Order {
static int issued = 0;
final int reference;
Order() {
issued++;
reference = issued;
}
}| Compared on | static | Instance |
|---|---|---|
| There is | One, for the whole class | One per object |
| Reached through | The class name — Order.issued | A reference — a.reference |
| Can read instance fields | No — there is no object to read them from | Yes |
| Exists | From the first time the class is loaded | From new until nothing points at it |
The third row is the one that produces the error everyone meets: a static method cannot touch an instance field, because it was not called on any object and has nothing to read the field from. That is also why main cannot use your fields without making an object first.
The decision rule. If the value would be the same for every object, or the method would ignore the object entirely, make it static. If it describes one object, it is an instance member. A static field holding something that varies per object is a bug waiting for a second object.