Lesson · Object Initialization & Memory
static: one per class, not one per object
15 min readstatic
static moves a member from the object to the class: one slot, one lifetime, no receiver. The counter that refused to count, the honest uses of class-level state, and why a mutable static is a global in disguise.
The counter that refuses to count
Start with a class that wants to know how many orders were ever created:
class Order { int count = 0; // one counter per order... Order() { count++; } // ...so this increments a fresh 0 every time } System.out.println(new Order().count); // 1 System.out.println(new Order().count); // 1 again, not 2
Predict before reading on. The increment ran twice, yet the count never passes 1. Each object received its own count; two objects, two counters, each touched once. Where could the counter live so every object shares one?
The fix: one slot per class
Move the counter from the object to the class with one keyword:
class Order { static int count = 0; // one slot, owned by the class Order() { count++; } // every object touches the same slot } new Order(); new Order(); System.out.println(Order.count); // 2
static int countcreates one slot when the class is initialised, not one per object.- The constructor still runs once per object, but every run increments the same shared slot.
- The count is read through the class,
Order.count, because the class is what owns it.
static means class-level: one slot, one lifetime, no receiver. The receiver is the object a call is sent to: in the demo's first.number() it is first, and inside the method it is this. Static members have none, because the class owns them, not any object. The keyword does not mean 'make it global' or 'make it fast'; it means 'this belongs to the type, not to an instance'.
One slot per class · one number per object
Class · Order
One slot, created at class initialisation, shared by every instance.
Instances · heap
no orders yet
Nothing has run yet. The class owns one shared slot; no orders exist.
static across declarations
The keyword appears in four places, always with the same meaning: the member belongs to the type.
| Declaration | What static changes |
|---|---|
| static field | One slot per class, initialised at class initialisation, shared by every instance and thread |
| static method | No receiver, no this; callable without an object; cannot read instance state directly |
| static block | Runs once at class initialisation, in source order with the static fields |
| static nested class | The nested class needs no enclosing instance; an inner class does |
Static members are read through the class, `Order.count`, not through an object. Calling a static method on an instance reference compiles but misleads readers; order.count looks like object state and is not.
Worked examples: class, method, block
One runnable program, three shapes of the keyword:
public class StaticParts { static class Envelope { private String to = "Ada"; static class Letter { // static nested class: stands alone String stamp() { return "priority"; } } class Card { // inner class: bound to an Envelope instance String address() { return to; } // reads that instance's private field } } static class Table { static final int[] POWERS; // blank static final: assigned in the block static int builds; // defaults to 0 before the block runs static { // runs once, at class initialisation POWERS = new int[4]; for (int i = 0; i < POWERS.length; i++) { POWERS[i] = 1 << i; // 1, 2, 4, 8 } builds++; } static int power(int index) { // static method: no receiver, no this return POWERS[index]; } } public static void main(String[] args) { Envelope.Letter letter = new Envelope.Letter(); // no Envelope object needed System.out.println(letter.stamp()); // priority Envelope envelope = new Envelope(); Envelope.Card card = envelope.new Card(); // an inner class is made through one System.out.println(card.address()); // Ada System.out.println(Table.power(3)); // 8: first touch initialises Table System.out.println(Table.builds); // 1: the block ran once } }
- Static nested class:
new Envelope.Letter()compiles with noEnvelopeobject anywhere, andLettercannot reachto. Drop thestaticandCardbecomes an inner class: it is created through an enclosing instance,envelope.new Card(), and reads that instance's field. - Static method:
Table.power(3)is called through the class with no receiver to pass; noTableobject is ever created, andPOWERSis reachable because statics freely see other statics. - Static block: the
static { ... }block runs once, whenTableis first touched, in source order with the field initialisers around it;buildsprints 1 no matter how often the class is used.
The static block is the class's constructor. It runs once per class loader, top to bottom with the field initialisers, before the first use; a blank static final field is legal exactly because the block assigns it before anyone can read it.
Instance state, class state
Side by side, the two kinds of state answer different questions:
| Instance member | Static member | |
|---|---|---|
| Answers | which object? | a fact about the type |
| Slots | one per object | one per class loader |
| Lives from | object construction | class initialisation |
| Needs a receiver? | yes, this | no |
- Shared means shared: a mutable static is one variable every object and thread reaches into, which is how counters, caches and configuration turn into surprises.
- static cannot see instance state: inside a static method there is no
this, so instance fields are simply out of scope. - Tests notice: static mutable state survives between tests, a classic source of order-dependent failures.
Default to instance members; reach for static when the fact belongs to the type. Constants, stateless helpers and counters are the honest cases; 'so I do not have to pass it around' is not.
Honest uses of static
The places where class-level ownership is the right shape:
- Stateless utilities:
Math.abs,Integer.parseInt. No object state, nothing to configure. - Constants:
static finalvalues named once; a compile-time constant is even inlined into callers by javac. - Factory methods: static methods that build instances, such as
List.of(...)andLocalDate.now(). - Genuinely one-per-JVM facts, with care: counters, registries and caches, which need a thread-safety story before they need a keyword.
Every static field is a global wearing a class name. Fine when it is final and immutable; a design decision the moment it mutates, because every code path, test and thread then shares it.
The static-or-instance playbook
Deciding for a member, in order:
- Does the value describe one object or the type itself? The object wins by default; the type must make its case.
- Does the method read or write instance fields? If yes it must be an instance method; if no, static is on the table.
- Would two instances disagreeing be a bug? That is exactly what a static field makes impossible, and what an instance field makes safe.
- Is the static member mutable? Then name its thread-safety strategy before writing it; otherwise keep it final.
Instance members answer 'which one?'; static members answer 'what is true of the type?' The compiler enforces the difference: static code cannot reach this.
A mutable static is a global variable wearing a class name
One slot, reachable from everywhere, living for the whole run. Counters, caches and configuration drift into static by convenience, and every code path, test and thread shares the consequences. Final immutable statics are constants; everything else needs a written thread-safety story and, ideally, a way to reset it between tests.
Interview angles
static versus instance members, in one breath?+
Instance members live per object and run against a receiver (the object the call is sent to; in first.number() the receiver is first, and inside the method it is this). Static members live per class, have no receiver, and are shared by every instance.
The compiler enforces the split: static methods have no this, so instance fields are out of scope inside them. Calling a static method through an object reference is legal but reads as a mistake. For fields: one slot per object against one slot per class, initialised at class initialisation.
class Counter { int own; // one per object static int shared; // one per class }
Common misconception: That static means 'shared across the JVM'. It is per class loader, which matters in application servers and plugin systems that load the same class more than once.
Follow-up: Why must main be static?
Why must main be static?+
Because the JVM calls it before any object of the class exists: there is no instance available to use as a receiver.
The launcher searches for exactly public static void main(String[]). A static entry point is the one call that can happen with zero objects created, which is precisely what starting a program needs.
public static void main(String[] args) { ... }
Common misconception: That main is special syntax. It is an ordinary static method whose signature the launcher happens to search for.
Follow-up: What happens if a class declares only a non-static main?
Can a static method call an instance method?+
Not directly: with no receiver, there is no object to invoke it on. It can call instance methods on objects it creates or receives.
The error message ('non-static method cannot be referenced from a static context') is the compiler pointing at step one of every call, the receiver, which does not exist in static code.
static void run(Order order) { // a static method inside Order // number(); // error: which object? there is no receiver here order.number(); // fine: the receiver is the argument new Order().number(); // fine: the receiver is the object it just created }
Common misconception: That the fix is marking the other method static. The fix is deciding which object should receive the call.
Follow-up: In one sentence, what is the receiver of a call?
Where do static fields live?+
With the Class object for that class: one slot per class loader, conceptually attached to the type rather than to any instance.
The JVM specification treats static fields as part of the class's state, not the per-object layout. The mental model 'one slot per class loader' predicts everything you will observe, including two independent copies when two loaders load the same class.
class Config { static int counter; } // one slot, not one per instance
Common misconception: That each object quietly carries the static field. Instances carry no copy at all, which is why one object incrementing it is visible from every other.
Follow-up: How many copies exist if two class loaders load the same class?
When is a mutable static dangerous?+
Until it has a thread-safety and test-isolation story. It is shared by every thread and survives between tests.
Two mature responses: keep the field final and immutable (a constant), or route mutation through a thread-safe structure with a documented reset. Test frameworks fight shared mutable state because parallel tests and repeated runs observe each other's leftovers.
static int requests; // every test sees the same number static final int LIMIT = 100; // constant: safe by construction
Common misconception: That statics are safe because they are 'just one variable'. One variable shared by many writers without coordination is exactly the problem.
Follow-up: How would you redesign a static cache so tests can isolate it?