In my opinion, there are no unsolvable problems due to which inner classes cannot have static members, and the vars used in anonymous classes should only be final. I think it was just the decision of language designers.
Compiler
turns it into this
class X { } class X$Y { private final X x; X$Y(X x) { this.x = x; } }
there is no reason why X $ Y cannot have static members. Syntax is not a problem either.
class X { class Y { static int x = 1; } void x() { Yx = 2; } }
as for static final int x = 1; different from static int x = 1; - the difference is that the former does not need initialization, it is a constant, and the latter requires an implicit static initialization block to place the code that will assign 1 x.
- final var goes into an anonymous class as constructor parameter
class X {void x () {final Integer x = 1; new Runnable () {public void run () {int y = x; }}; }}
actual anonymous class
class X$1 { private final Integer x; X$1(Integer x) { this.x = x; } ...
the only reason the external variable should be final is that otherwise it would look like we can change it from the internal code of the class
void x() { Integer x = 1; new Runnable() { public void run() { x = 2; } ...
but this is not so, because the inner class works with a copy
source share