Why Method-local inner classes can only be abstract or final. What would be problem with other modifiers ???
What is the use of other modifiers. Can you declare a local variable static or public or private?? No declarations inside of a method can be static or public or private or protected because it doesn't makes sense. Local variables are local to the method, so there is no point in them being public or private etc or even static for that matter...
Hii .. just wanted to share why a method local inner class can access final variables...
As you must be knowing that when we compile a class having a method local inner class , the compiler makes 2 class files.
e.g. outer.class and outer$inner.class
Now imagine , if you could pass non final variables to a function inside the inner class. How will the JVM pass a variable from one class to a function in another class.
To solve this problem , the JVM makes a requirement that the developer mark the variable as FINAL.
How does it solve the problem?
when you mark a variable as final in the outer class , the compiler places a hidden variable (e.g. val$var ) in the compiled inner class file.
The value of this hidden variable and the final variable declared in the outer class will be same. And as it is final , it cannot change at the runtime. Also , the final variables has to be assigned before the compilation.
Below is code that demonstrates the discussion points. Note that the outer class does not reference the inner class. It references an interface that the inner class implements. Note also that although the inner class can not be declare public, its functions can.