AP® Computer Science A · Unit 3 · Topic 3.7
static Variables Shared by Every Object
A static variable belongs to the class itself, not to any one object, so every object shares exactly one copy of it in memory. Change it through any object and every object sees the new value.
Every instance variable gets its own slot in memory for every object you build — give each Dog object a name field, and three dogs mean three separate name slots. static flips that. Write static int count; in a class, and that field lives with the class itself, in one place, before any object even exists. No matter how many objects you create, they all point back to that same single variable. Read it through object a or object b and you get the identical value, because there's nothing to tell apart — it's one box, not many.
This matters whenever objects need to agree on something collective: how many of them exist, a running total, a shared configuration setting, a next-available ID. An instance variable can't do that job, because each object's copy is deaf to what the others are doing. A static field can, because there's only one copy to begin with.
This sits right next to constructors because the two combine naturally: a constructor runs once per object, so incrementing a static field inside one gives you a live count of every object ever built. It also connects to the private vs shared theme of the unit — fields are usually locked down with private for encapsulation, but static changes who the field is shared with, not whether outsiders can touch it directly.
Key terms
- static variable
- A field that belongs to the class itself, with exactly one shared copy used by every object of that class.
- instance variable
- A field that belongs to an individual object, with a separate copy stored for each object created.
- constructor
- The block of code that runs once each time a new object is built, often used to initialize fields.
- class
- A blueprint that defines what fields and methods its objects will have.
Watch it explained
- How it worksHow does a static variable live with the class while instance variables live with objects?
- Worked exampleTrace a static counter incremented in the constructor as four objects get created.
- Common mistakeWhy doesn't each object get its own private copy of a static field?
- Going furtherWhat changes when one object writes to the static field while others are already alive?
Check yourself
End of topic.