liveBook · Manning

Static field

As explained in 100 Java Mistakes and How to Avoid Them

A static field is a Java class variable whose storage is associated with the class rather than with each object instance.

A static field is associated with the class, so one field value is shared by every object of that class. Accidentally using static where an instance field is intended can leak one object's data into another object's context without raising an exception. section 3.11 section 3.12

Accidental sharing

In the Person example, private static String name means that setName on one Person changes what getName returns for every Person. The defect may remain hidden when objects are created and discarded sequentially, but simultaneous users can receive one another's data. section 3.11

Check static fields before accepting the apparent simplicity of a passing test:

  • Use an instance field when each object needs independent state; reserve nonfinal static fields for limited, deliberate uses. section 3.11
  • Do not assume final removes sharing: a static final mutable collection can still hold data shared by every object. section 3.11
  • Test concurrent and overlapping object use, not only sequential use, because shared state can pass simple tests and fail as usage grows. section 3.11
  • Review IDE highlighting and enable relevant inspections: IntelliJ IDEA reports assignments to static fields from instance contexts, while SonarLint reports S2696 by default. section 3.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains sharing, sequential-test masking, mutable static-final state, concurrency consequences, and static-analysis detection.
Examples
Uses a shared Person name and a static final TreeWalker queue to demonstrate cross-object and cross-thread state leakage.
What it assumes
Assumes Java familiarity and distinguishes static fields from regular instance fields rather than teaching object state from zero.
What you can do after
Diagnose/debug with code review, concurrency-focused tests, IDE highlighting, and static-analysis inspections.
How it connects
Connects static fields with instance fields, mutable collections, concurrency, privacy, security, and static analysis.

Also explained in

Compare how 7 books explain static field →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.