Sub topic 13
When to Use `static` and When to Avoid It
Assume you can define classes, create objects with new, call instance methods, use access modifiers, and override methods through inheritance. This chapter focuses on choosing between class-level members and object-level members.
Use `static` for Class-Wide Concepts
Use static when a value or operation belongs to the class as a whole rather than to one object.
Good candidates include:
- Constants that never change.
- Pure operations whose result depends only on their arguments.
- Counters or registries that intentionally represent one shared resource.
- Named factory methods that create objects.
- Utility methods that do not need object state.
- A static nested class that logically belongs to its outer class but does not need an outer object.
A static field has one value for the class in a running Java Virtual Machine. Every object of that class sees the same field. A non-static field has a separate value in every object.
A static method is also attached to the class. Call it with the class name:
public final class Tax {
public static final double RATE = 0.20;
private Tax() {
// Prevents accidental construction.
}
public static double addTax(double amount) {
return amount * (1 + RATE);
}
public static void main(String[] args) {
System.out.println(Tax.addTax(100.0));
}
}RATE is shared and immutable. addTax does not need a Tax object, because it uses only its parameter and the class constant. The private constructor prevents meaningless instances.
Avoid `static` for Object-Specific State
Do not make a field static merely because many methods need it. If the value describes one object, keep it as an instance field.
For example, each User should have its own name and permissions. Making those fields static would cause one user's data to replace another user's data.
Avoid mutable static fields when possible:
public final class SessionStore {
public static final Map<String, String> SESSIONS = new HashMap<>();
}This design creates global state. Any part of the application can change the map. Tests can affect one another, requests can interfere with one another, and the lifetime of the data becomes difficult to control.
Passing a SessionStore object to the code that needs it makes the dependency visible. It also lets tests provide a separate store.
Compare the Main Trade-Offs
| Choice | Strength | Common cost |
|---|---|---|
| `static final` constant | Clear shared value | May be fixed for the whole process |
| Static pure method | Simple to call and test | Cannot use polymorphism or object state |
| Mutable static field | Convenient shared data | Hidden dependencies and thread-safety risks |
| Instance field or method | Encapsulates object state | Requires an object and dependency management |
A static method cannot be overridden dynamically. A subclass can declare a method with the same signature, but that method hides the parent method. Java selects a static method from the declared reference type, not the runtime object type. Use instance methods when subclasses must provide different behavior.
Check Thread Safety
Shared mutable static state is shared between threads. An operation such as count++ is not one indivisible action. Two threads can read the same value and lose one update.
Use synchronization or a concurrent type when shared state is necessary:
import java.util.concurrent.atomic.AtomicInteger;
public final class IdGenerator {
private static final AtomicInteger NEXT = new AtomicInteger();
private IdGenerator() {
}
public static int next() {
return NEXT.incrementAndGet();
}
}Thread safety does not solve every design problem. A global generator may be safe to update but still make tests depend on execution order.
Make the Decision
Ask these questions:
- Does the member describe the class or one object?
- Does the method need
thisor instance fields? - Must a subclass replace the behavior?
- Can shared mutable state create races or test interference?
- Would passing an object make the dependency clearer?
Use static when the answer is genuinely class-wide. Otherwise, prefer an instance member and explicit dependencies.
Exercise
A Report object has a title, while formatting a number needs only the number and a fixed format rule. Which should be static?
Show answer
Keep title as an instance field. A formatting method can be static if it needs no report-specific state, and the format rule can be a static final constant.