Card 07/ 09
static vs Instance Members
A counter for unique order numbers, on every order, gives every order its own counter starting at one.
A static field or method belongs to the class, so there is exactly one of it however many objects exist. Everything else is an instance member and belongs to one object. The choice decides how many copies there are and what the member can reach.
Every order needs a reference number, unique across all orders. Putting the counter on each order gives every order its own counter, all of them starting at one. Making it static gives the class one counter that every constructor call increases:
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.
← → move through sections and cards