Mystery of Accessibility in Local Inner Classes

In Java, I'd always known that whenever I wanted to pass a local variable into a (possibly anonymous) inner class without any getter/setter code I had to declare the variable as final, or alternatively it had to be an instance variable of the parent class.

If you just read that sentence and had no idea what I said, please feel free to skip the rest of this post.

What I didn't know was why this was necessary. Clearly the assumption is that Java does some trickery, but needs the variable to be a constant value. Then I read this blog post and learnt that essentially that is what happens. Perhaps more interesting is that inner classes are only handled at the compiler level, in other words the JVM is completely oblivious to their existence.

If you are a Java dev and have a few minutes spare, this blog post is very interesting. I'm always interested in learning new aspects of the Java language/runtime, and I have a feeling I'm going to need to find a book on Java bytecode sooner or later.

Thoughts on “Mystery of Accessibility in Local Inner Classes”