Static members in inner classes
Define static members in inner classes without requiring static nested classes.
Code Comparison
✕ Java 8
class Library {
// Must be static nested class
static class Book {
static int globalBookCount;
Book() {
globalBookCount++;
}
}
}
// Usage
var book = new Library.Book();
✓ Java 16+
class Library {
// Can be inner class with statics
class Book {
static int globalBookCount;
Book() {
Book.globalBookCount++;
}
}
}
// Usage
var lib = new Library();
var book = lib.new Book();
Why the modern way wins
More flexibility
Inner classes can now have static members when needed.
Shared state
Track shared state across instances of an inner class.
Design freedom
No need to promote to static nested class just for one static field.
Old Approach
Must use static nested class
Modern Approach
Static members in inner classes
Since JDK
16
Difficulty
intermediate
JDK Support
Static members in inner classes
Available
Widely available since JDK 16 (March 2021)
How it works
Before Java 16, only static nested classes could contain static members. Inner (non-static) classes couldn't have statics because they required an enclosing instance. Java 16 relaxes this restriction, allowing static fields, methods, and even nested types in inner classes.
Related Documentation