static
Normally each object has its own copy of every field. Sometimes you want one thing shared by all objects. static does this. It puts a member on the class itself, not on each object.
Every object sees the same class-level member. It is not a separate copy.
- Static field: one shared variable for the whole class, such as the singleton instance or a registry map.
- Static method: called on the class, not on an object, such as
Main.main(args),LogisticsFactory.getLogistics("road")orJudgeAnalytics.getInstance(). - Static block:
static { ... }runs once, when Java first loads the class. It is often used to fill a registry.
You don’t need new to use static members: ClassName.staticMethod(), ClassName.staticField.
final
final means a variable can be given a value only once. After that, it cannot be reassigned. If the variable holds an object, it cannot point to a different object. But the object itself can still change (it is mutable).
A final label stays attached to the same value or object. It does not freeze what is inside that object.
- Final variable: set once, at the declaration or in the constructor, and then never reassigned.
- Final field: the same rule for object fields, such as
private final String contentin a memento. - Final static field: a value shared by the whole class that is set once, such as
private static final Map<String, EmailTemplate> templates.
Using final on fields helps make objects immutable (they cannot change after creation) or marks a dependency as “set once.”
Examples
// static method = call without an object
public class LogisticsFactory {
public static Logistics getLogistics(String mode) {
if (mode.equalsIgnoreCase("Air")) {
return new Air();
} else if (mode.equalsIgnoreCase("Road")) {
return new Road();
}
throw new IllegalArgumentException("Unknown logistics mode: " + mode);
}
}
// Usage: Logistics l = LogisticsFactory.getLogistics("road");// static block = run once when class loads (a fragment from inside EmailTemplateRegistry;
// it needs import java.util.*;)
private static final Map<String, EmailTemplate> templates = new HashMap<>();
static {
templates.put("welcome", new WelcomeEmail());
}// final = set once, never reassigned
private final Stack<EditorMemento> history = new Stack<>();
private final String content; // Set in constructor, then immutableWhere you see it in this repo
main: everypublic static void main(String[] args). The entry point is static, so Java can start without creating an object.- Factory:
LogisticsFactory.getLogistics(String)is a static factory method. - Singleton:
JudgeAnalytics.getInstance()is static. The nested holder class isprivate static class JudgeAnalyticsHolderwithprivate static final JudgeAnalytics INSTANCE. - Prototype registry:
EmailTemplateRegistryhas a static map and a static block to fill it.getTemplate(String)is static. - Builder / Memento:
private finalfields for immutable or stable state.