Card 07/ 09

ComparisonDifficulty: Intermediate1 min

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:

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.