library
beginnerThe static Keyword
Know every use of static in Java: fields, methods, blocks, nested classes, and imports.
The static keyword means 'belongs to the class, not to instances.' It has five uses in Java:
Static = a shared whiteboard in the office (one copy, everyone reads/writes the same board). Instance = personal notebooks (each person has their own).
Key Concepts
1
1. Static fields — one copy shared across all instances. Used for constants (static final), counters, caches. Stored in the metaspace (not heap). Initialized when the class is loaded.
2
2. Static methods — called on the class, not an instance. Cannot access instance fields or this. Used for utility methods (Math.max), factory methods (List.of), and main().
3
3. Static blocks — run once when the class is loaded, in declaration order. Used for complex static field initialization (loading native libraries, reading config files).
4
4. Static nested classes — inner classes declared static. They don't hold a reference to the enclosing instance. Preferred over non-static inner classes when the inner class doesn't need the outer's state.
5
5. Static imports — import static java.lang.Math.PI lets you use PI directly instead of Math.PI. Useful for constants and utility methods but hurts readability when overused.
6
Static methods cannot be overridden — they can be hidden (subclass declares same signature) but dispatch is by reference type, not object type. This is why static methods aren't polymorphic.