Question
About Inner class may be 'static' (version 2025.2):
"When using Java 17 or before"
What happened in Java 18+ to make static less important for inner classes? I can't find any info. It's strange to see Java 17 and earlier specifically referenced for this inspection. If it's not a mistake, I'd appreciate the relevance of the Java version described explicitly.
Answer
According to Oracle's blog: The hidden gems in Java 18: The subtle changes , the reason is as follows:
Enclosing instance fields are omitted from inner classes that don’t use them
Prior to JDK 18, when the Java compiler compiled an inner class, it always generated a private synthetic field with a name that started with
this$to reference the enclosing instance—even if the inner class did not reference its enclosing instance and the field was unused.Beginning with JDK 18, unused
this$fields are removed; the field is generated only for inner classes that refer to their enclosing instance.For example, consider the following program:
class M { class T { } }Before JDK 18, the program would be translated as follows:
class M { class T { private synthetic M this$0; T(M this$0) { this.this$0 = this$0; } } }Starting in JDK 18, the unused
this$0field is omitted.class M { class T { T(M this$0) { } } }If the enclosing instances were previously reachable only via a reference in an inner class, the change might cause them to be garbage collected sooner. This is usually desirable because it eliminates a potential source of memory leaks when inner classes are created that are meant to outlive their enclosing instance.
Note that subclasses of
java.io.Serializableare not aected by this change.
Comments
0 comments
Please sign in to leave a comment.