Class Attributes: State

Class Attributes: State in Java: Every lathe in the workshop carries a steel plate riveted to its frame.

The Analogy: The Machine Plate And The Workshop Noticeboard

Every lathe in the workshop carries a steel plate riveted to its frame. Stamped on it are the serial number, the hours it has run, and the date it was last serviced. There is one plate per machine, it was fixed on at the factory, and reading the plate on lathe 31 tells you nothing whatsoever about lathe 32. Two machines delivered on the same day drift apart the moment they are used differently, and the plates are the record of that drift.

By the door there is a single noticeboard. On it are the current shift number and the service interval the whole shop works to. Neither of those is a property of any lathe. Giving every machine its own copy of the shift number would guarantee that within a week they disagreed, and the question "what shift is it" would have as many answers as there are machines. One board, one answer, and changing it changes it for everybody at once. That is a static field.

There is a third kind of writing in the workshop, and it obeys a different rule. A plate comes out of the stamping shop with the hours field reading 0000 and the service date left blank -- not "unknown", a defined blank that means the machine has never been serviced. The foreman will accept that. What he will not accept is a scrap of paper from your pocket with a figure on it that you have not filled in, because a scrap has no defined blank state; whatever is written on it is whatever the last person wrote. Fields get guaranteed defaults; local variables get nothing, and the compiler refuses to read one you have not written to.

The failures are all about reach. A plate that anybody in the shop can unrivet and restamp is not a record, and a public mutable field is not state -- it is a suggestion. A noticeboard written by two supervisors at the same instant ends up carrying one supervisor's figure and no trace of the other's, which is a mutable static field and two threads. And the worst of the three: a plate whose hours field was wired to the noticeboard by mistake, so that every machine in the shop reports the same hours run and the service schedule is quietly nonsense. That is one word, static, in front of the wrong field.


Syntax or Core Structure

A field declared inside the class body but outside any method is an attribute. Without static there is one per object; with static there is one per class.

public class Lathe {

    static final int SERVICE_HOURS = 500;
    static int shift = 1;
    static int built;

    final String bay;
    String serial;
    int hoursRun;
    boolean serviced;

    Lathe(String serial, String bay) {
        this.serial = serial;
        this.bay = bay;
        built++;
    }

    public static void main(String[] args) {
        Lathe a = new Lathe("L-31", "north");
        Lathe b = new Lathe("L-32", "south");

        a.hoursRun = 620;
        b.hoursRun = 90;
        b.serviced = true;

        shift = 2;

        System.out.println("a hours   " + a.hoursRun);
        System.out.println("b hours   " + b.hoursRun);
        System.out.println("a bay     " + a.bay);
        System.out.println("a service " + a.serviced);
        System.out.println("b service " + b.serviced);
        System.out.println("shift     " + shift);
        System.out.println("via a     " + a.shift);
        System.out.println("built     " + built);
        System.out.println("limit     " + SERVICE_HOURS);
    }
}

Output:

a hours   620
b hours   90
a bay     north
a service false
b service true
shift     2
via a     2
built     2
limit     500

a.serviced prints false although no line ever assigned it: that is the guaranteed default for boolean, and it is the whole reason a fresh object is usable before any setter is called. built reached 2 because the constructor incremented a field that belongs to the class rather than to either lathe. And a.shift is a warning sign rather than a feature -- it compiles, it resolves at compile time to Lathe.shift, and it reads as though shift were a property of lathe a, which is exactly the misreading that gets a shared field mistaken for a private one.


Technical Depth: Where Fields Live, When They Are Initialised, And What A Default Actually Guarantees

Three storage kinds, three sets of rules

Instance fieldStatic fieldLocal variable
One copy perobjectclassmethod invocation
Default valueyes, by typeyes, by typenone at all
Set up whenthe object is constructedthe class is first usedthe declaration runs
Lives untilthe object is unreachablethe class is unloadedthe method returns
Read before writtenlegal, gives the defaultlegal, gives the defaultcompile error
Visible to other threadsif the object is sharedalwaysnever

The last row is the one that costs money. A local variable cannot be seen by another thread, an instance field can only be seen by a thread that has been given the object, and a static field is reachable from every thread in the process by name. Adding static to a field does not just change how many copies exist -- it changes who can reach it.

The initialisation order is fixed and worth memorising

public class Order {

    static StringBuilder log = new StringBuilder();

    static int firstField = note("static field");
    static { note("static block"); }

    int instField = note("instance field");
    { note("instance block"); }

    Order(String who) {
        note("constructor " + who);
    }

    static int note(String s) {
        log.append(s).append(" / ");
        return 0;
    }

    public static void main(String[] args) {
        note("main starts");
        new Order("one");
        String[] steps = log.toString().split(" / ");
        for (int i = 0; i < steps.length; i++) {
            System.out.println("step " + (i + 1) + "  " + steps[i]);
        }
    }
}

Output:

step 1  static field
step 2  static block
step 3  main starts
step 4  instance field
step 5  instance block
step 6  constructor one

Static field initialisers and static blocks run once, in the order they are written, when the class is first used -- which is before main in this file, because using main is using the class. Then, on every new, the instance field initialisers and instance initialiser blocks run in textual order, and only then does the constructor body run. The consequence that catches people is the last one: anything the constructor body sets has already been overwritten once by the field initialiser, and a field initialiser cannot see a constructor parameter. Pick one place to initialise each field and stay there.

Defaults are guaranteed for fields and forbidden for locals

public class Defaults {

    static int si;
    static boolean sb;
    static double sd;
    static String ss;
    static char sc;

    public static void main(String[] args) {
        System.out.println("int      " + si);
        System.out.println("boolean  " + sb);
        System.out.println("double   " + sd);
        System.out.println("String   " + ss);
        System.out.println("char     " + (int) sc);
        System.out.println("is nul   " + (sc == 0));
    }
}

Output:

int      0
boolean  false
double   0.0
String   null
char     0
is nul   true

Every numeric type defaults to zero, boolean to false, char to code point zero, and every reference type to null. These are specified, not incidental -- the JVM zeroes the memory before the constructor sees it. Write int n; System.out.println(n); inside a method instead and it will not compile: the message is that n might not have been initialised. The asymmetry is deliberate. A field can be written by any method in any order, so the language guarantees a floor rather than trying to prove anything; a local has exactly one scope, so the compiler can prove it and therefore insists.

Instance fields can be shadowed, and this is the only cure

public class Shadow {

    static class Bay {
        String name = "north";

        void broken(String name) {
            name = name;
        }

        void fixed(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args) {
        Bay one = new Bay();
        Bay two = new Bay();

        one.broken("south");
        two.fixed("south");

        System.out.println("broken   " + one.name);
        System.out.println("fixed    " + two.name);
    }
}

Output:

broken   north
fixed    south

A parameter with the same name as a field hides the field for the whole method body, so name = name assigns the parameter to itself and does nothing at all. It compiles cleanly; some build configurations will warn about self-assignment, and most do not. this.name is not decoration -- inside a method whose parameter shadows a field, it is the only way to name the field.

static final constants are copied into everything that reads them

DeclarationValue copied into readersA change requires
static final int N = 500;yes, at compile timerecompiling every class that reads it
static final String S = "north";yes, at compile timerecompiling every class that reads it
static final int N = compute();norecompiling the owner only
static final List<String> L = ...norecompiling the owner only
static int n = 500;norecompiling the owner only

A static final field of a primitive or String type whose initialiser is a compile-time constant is a constant variable in the language's terms, and the compiler is allowed to substitute its value directly into every use site in every other class. Change the constant, rebuild only its own module, ship it, and the other modules go on enforcing the old figure with no error anywhere. That is why version-sensitive limits belong behind a method or a non-constant initialiser.

The other row worth noticing is the List. final freezes the reference, not the object: static final List<String> BAYS can still have items added to it from anywhere in the process, by anyone, at any time. A constant collection needs List.of(...) or an unmodifiable wrapper as well as final.


Real World Example: A Meter Register Where One Number Belongs To The Site And The Rest Belong To The Meters

Three meters on one site. The serial, the reading and the fault flag are facts about a particular meter. The tariff is a fact about the site, and the whole point of it being one number is that changing it moves every bill at once.

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Meter {

    static final int MAX_KWH = 9000;

    static int tariffPence = 27;
    static int installed = 0;
    static int rejected = 0;

    final String serial;
    int readingKwh;
    boolean faulty;

    Meter(String serial) {
        this.serial = serial;
        installed++;
    }

    void submit(int kwh) {
        if (kwh < 0 || kwh > MAX_KWH) {
            faulty = true;
            rejected++;
            return;
        }
        readingKwh = kwh;
    }

    int billPence() {
        return readingKwh * tariffPence;
    }

    public static void main(String[] args) {
        List<Meter> site = new ArrayList<Meter>();
        site.add(new Meter("M-101"));
        site.add(new Meter("M-102"));
        site.add(new Meter("M-103"));

        site.get(0).submit(120);
        site.get(1).submit(9400);
        site.get(2).submit(45);

        for (int i = 0; i < site.size(); i++) {
            Meter m = site.get(i);
            System.out.println(String.format(Locale.ROOT,
                    "%-6s kwh %4d  faulty %-5s  bill %5d",
                    m.serial, m.readingKwh, m.faulty, m.billPence()));
        }

        int before = 0;
        for (int i = 0; i < site.size(); i++) {
            before += site.get(i).billPence();
        }

        tariffPence = 31;

        int after = 0;
        for (int i = 0; i < site.size(); i++) {
            after += site.get(i).billPence();
        }

        System.out.println("installed " + installed);
        System.out.println("rejected  " + rejected);
        System.out.println("tariff    " + tariffPence);
        System.out.println("before    " + before);
        System.out.println("after     " + after);
        System.out.println("uplift    " + (after - before));
        System.out.println("ceiling   " + MAX_KWH);
    }
}

Output:

M-101  kwh  120  faulty false  bill  3240
M-102  kwh    0  faulty true   bill     0
M-103  kwh   45  faulty false  bill  1215
installed 3
rejected  1
tariff    31
before    4455
after     5115
uplift    660
ceiling   9000

There is one test for whether a field should be static, and it is worth applying out loud: if I install a fourth meter, does this value need a fourth copy? serial, readingKwh and faulty do -- three meters give three independent answers, and that is the entire reason they are instance fields. tariffPence does not; a fourth meter on the same site is billed at the same rate, and giving it its own copy would create a system in which the site's tariff has four values and no way to say which is correct.

The pair of totals shows what a static field actually buys. One assignment -- tariffPence = 31 -- moved every bill on the site by 660 pence without touching a single Meter object, and no meter had to be told. That reach is precisely what makes the keyword dangerous as well as useful, because nothing in the declaration of billPence() hints that its result depends on a value any code anywhere in the process can change between two calls.

M-102 is worth reading carefully. Its reading was rejected, so readingKwh still holds the guaranteed default of 0 and it bills zero pence -- a defined, safe state that needed no special-case code anywhere. But look at what a zero reading cannot tell you: a meter that read zero because nobody has submitted anything and a meter that genuinely consumed nothing produce identical output. That is the whole justification for faulty existing as a separate field, and it generalises -- whenever a default value is also a legitimate value, you need a second field to carry the difference.

The honest limits, and the design flaw here is a real one. installed and rejected are mutable static counters, and static was the wrong choice for both. Because they belong to the class rather than to a site, a second site created in the same process adds to the first site's totals and there is no way to separate them; because they are unsynchronised, two threads constructing meters will interleave installed++ and lose increments with no error; and because they are never reset, a long-running process reports numbers that mean nothing. All three counters belong on a Site object, and tariffPence belongs there too -- as it stands, one JVM can bill exactly one tariff, so serving two regions means two processes or wrong invoices. Beyond that, billPence() returns int with no overflow guard: at the ceiling it is 9000 times 27, comfortably small, but a mistyped tariff of 3000000 wraps silently and produces a negative bill. And MAX_KWH is a compile-time constant, so its value is baked into every class that reads it; raise the ceiling, rebuild only this file, and the validation elsewhere in the system quietly keeps rejecting at 9000.


Common Mistakes

  1. Putting static on a field that belongs to the object. Every instance then shares one value, so the second object silently overwrites the first one's state. Apply the test: would a fourth instance need a fourth copy?
  1. Leaving static off a field that belongs to the class. Now every instance carries its own copy of something there should be one of, they drift apart, and "what is the current tariff" has as many answers as there are objects.
  1. Writing name = name when a parameter shadows a field. It assigns the parameter to itself and the field is untouched. It compiles, and most builds will not warn. Use this.name = name.
  1. Treating a field's default as proof it was set. A field reads 0 whether nobody assigned it or somebody assigned zero. If those two cases differ in meaning, you need a second field, a sentinel outside the valid range, or a wrapper type that can be null.
  1. Confusing the field rule with the local rule. Fields get guaranteed defaults; locals get a compile error. Moving a variable from a field to a local, or the reverse, changes whether "I forgot to initialise it" is caught at build time or shipped.
  1. Public mutable fields. public int hoursRun is not state, it is an open invitation: anything in the program can set it to anything at any time, and no validation you write in a setter will ever run.
  1. Reading a static member through an instance reference. a.shift compiles and reads exactly like an instance field, which hides the fact that the value is shared with every other object and every other thread. Write Lathe.shift.
  1. Believing static final on a collection makes it constant. final freezes the reference; the list behind it can still be added to from anywhere. Use List.of(...) or an unmodifiable wrapper.
  1. Mutable static state with no synchronisation. A static counter incremented from two threads loses increments silently -- count++ is a read, an add and a write, and nothing keeps them together. Use AtomicInteger, or better, stop using static state.

Best Practices

  • Decide static with one question. Would a second instance need its own copy of this value? Yes means instance field; no means the value belongs to something else, which is often a class you have not written yet rather than the static keyword.
  • Make fields private final by default and relax only under pressure. private means you can change the representation later; final means the compiler proves nothing reassigns it, and a reader can stop looking for the place that does.
  • Initialise each field in exactly one place. Field initialiser or constructor, never both -- the initialiser runs first and the constructor overwrites it, so having both leaves a line of code that can never affect anything.
  • Use this.x = x and keep the parameter name identical to the field. Renaming the parameter to newX to dodge the shadowing hides the relationship and reads worse; this is exactly the tool for it.
  • Never return or accept a reference to mutable internal state. A getter that hands back the live array or list has made the field public with extra steps.
  • Keep genuinely global data behind an object, not behind static. A Site with a tariff and two counters can be created twice, reset, injected into a test and reasoned about; three static fields can do none of those things.
  • Separate "absent" from "zero" explicitly. A companion boolean, an Optional, or a sentinel documented as impossible in the domain -- but pick one and say so, because the default value will not tell you.
  • Put version-sensitive limits behind a method, not a static final constant. Constant variables are inlined into every reader at compile time, so a limit that will ever change should be static int limit() rather than static final int LIMIT.

Practice Exercises

  1. The Second Site. Create two groups of meters in one run and print installed and rejected after each group. Show that the second group's figures include the first group's. Then introduce a Site class that owns tariffPence, installed and rejected as instance fields, give Meter a reference to its site, and rerun the same test -- the two sites must now report independently, and MAX_KWH should be the only static member left.
  1. The Absent Reading. Add a fourth meter and submit nothing to it. Print all four bills and show that the untouched meter and a genuine zero-consumption meter are indistinguishable. Fix it twice: once with a boolean hasReading field, and once by changing readingKwh to an Integer that starts null. Print what billPence() has to do in each version and say which you would ship and why.
  1. The Shadowed Setter. Write void setSerial(String serial) { serial = serial; } on Meter, call it, and show that the serial did not change. Then write the same bug in a constructor and show that the field ends up null rather than keeping its old value. Fix both with this, and finally rewrite serial as a private final field so that the broken setter cannot be written at all.