liveBook · Manning

Instance variable

As explained in 100 Java Mistakes and How to Avoid Them

An instance variable is data associated with a particular object, rather than shared across all instances of its class or type.

An instance variable, or regular field, stores data separately for each object of a class. A static field instead has one shared instance for the class, so using static where an instance variable is intended changes object-local state into shared state. section 3.11 section 3.12

The accidental static field

class Person { private static String name; public void setName(String newName) { name = newName; } public String getName() { return name; } } Here, every Person shares name. Setting one person's name changes what another person reads. Declaring name as a regular instance field keeps each object's value separate. section 3.11

This mistake can survive simple tests when objects are created and discarded one at a time. Under simultaneous use, shared state can leak between users or threads without raising an exception, creating incorrect behavior and possible privacy or security violations. section 3.11

Inspect static nonfinal fields carefully and consider whether each belongs to the class or to each object. IDE inspections can report static-field writes from instance methods, but static final does not guarantee isolation when it refers to mutable data such as a collection. section 3.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains per-object versus per-class storage, failure under concurrency, mutable static state, and applicable inspections.
Examples
Uses a Person name field and a concurrent TreeWalker queue to expose shared-state leakage.
What it assumes
Assumes familiarity with Java classes, objects, fields, and the static modifier.
What you can do after
Diagnose accidental static state by comparing field ownership with object usage and applying IDE or SonarLint inspections.
How it connects
Connects instance variables with static fields, object instances, mutable collections, concurrency, and static analysis.

Also explained in

Compare how 4 books explain instance variable →

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.