Objects, Classes & OOP Design
Static Members
Static fields and methods belong to the class, not to any instance — shared state, factory methods, utilities, and constants. Use them deliberately: statics are procedural islands in an object-oriented sea.
- One copy per class, shared by all instances (per class loader)
- Static methods cannot touch instance state or
this - Constants:
static final,UPPER_SNAKE_CASE - Static initializer blocks run once at class initialization
- Mutable static state is a concurrency hazard and a testing obstacle
public class IdGenerator {
public static final int MAX_ID = 1_000_000; // constant
private static final AtomicLong next = new AtomicLong(1); // shared, thread-safe
public static long nextId() { // class-level behavior
return next.getAndIncrement();
}
}Typical legitimate uses: constants, pure utility functions (Math.max), and static factory methods (Constructors Initialization). The main method is static precisely because no object exists before the program starts.