This question already has an answer here:
I'm reading about anonymous classes in java and it says you can access the methods of the enclosing class, but not the local variables. Why is it like this? I'm talking about this:
EDIT: The older example was incorrect not reflecting what I meant. This should be a better example according with what its being written here in the section "Accessing members of enclosing class" http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html.
public class MyClass {
public interface SomeInterface{
public void someOtherMethod();
}
public void someMethod(int someLocalVar) {
SomeInterface myClass = new SomeInterface(){
public void someOtherMethod(){
someLocalVar = 0; // This must be final to work
}
}
}
}
So what problem is this restriction solving?
An anonymous class object can have a lifetime that lasts longer than the method that created it, but it cannot last longer than the lifetime of the parent object.
Consider the following
Which 'a' variable is the Runnable going to modify. Cannot change the one local to the method, because the method is no longer on the stack.
Inner classes can access
final
variables of enclosing classes.Here's an interesting memo:
This comes from early version Java Inner Classes Specification.
Official specification URL, referred eg from VM spec 2.14 is gone for link rot: http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc.html
January 17, 1999 snapshot can be obtained at wayback machine though, respective spec section is References to local variables.
The way how things are supposed to work, is described as follows (I marked most relevant statement bold):
You see, language designers wanted value of copied local variable to be "consistent" every time such a copy is created. Their motivation was most likely that developers would need not worry to look outside of the copy of inner class to check whether it has been changed out there:
Note although spec example uses named class, same reasoning applies to anonymous classes: