Card 07/ 09

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.

java
class Order {
    static int issued = 0;
    final int reference;

    Order() {
        issued++;
        reference = issued;
    }
}
What a static member and an instance member each belong to
Compared onstaticInstance
There isOne, for the whole classOne per object
Reached throughThe class name — Order.issuedA reference — a.reference
Can read instance fieldsNo — there is no object to read them fromYes
ExistsFrom the first time the class is loadedFrom 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.