Language intermediate

Static members in inner classes

Define static members in inner classes without requiring static nested classes.

✕ 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();
🔓

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
Static members in inner classes
Available

Widely available since JDK 16 (March 2021)

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.

Share 𝕏 🦋 in