Static members in inner classes
Define static members in inner classes without requiring static nested classes.
Porównanie kodu
✕ 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();
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Must use static nested class
Nowoczesne podejście
Static members in inner classes
Od JDK
16
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Static members in inner classes
Dostępne
Widely available since JDK 16 (March 2021)
Jak to działa
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.
Powiązana dokumentacja