Class ExampleClass{
MyObj obj;
methodA(new ClassA(){
@override public void innerMethodA(){
//code...
}
});
}
So far so good.
Now, in order to use obj that was declared before the method I usually define it as final. I don't really understand why but i do because the compiler asks. In this code i see in innerMethodA() the usage of ExampleClass.this.obj()
without final.
My questions :
1. why do I have to put final when I use obj? 2. what is ExampleClass.this ? Notice that ExampleClass is the Class not an instance. then what is the "this"? if it has several insta开发者_开发技巧nces? 3. What happens if I change the obj while the inner method runs (in my code inner method runs in a loop so I plan on changing it . will it explode?)- You have to use
final
when you capture the variable of a local variable... not an instance variable of the enclosing class. ExampleClass.this
is a reference to the instance ofExampleClass
associated with the instance of the subclass ofClassA
. In your case, it will be the same asthis
withinmethodA
.- It won't explode - it will just change the value of
obj
. Think of it as capturing the value ofExampleClass.this
(so you can't change that) but you can change the data within the object referred to byExampleClass.this
.
- There are no "true" closures (functions that capture scope) in Java. See e.g.http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-different
- You can use this form to reference ambiguous methods / variables in the scope of "ExampleClass".
- You cannot change the reference. What you can do is use an indirection, e.g. a final reference to an object that can swap it's values. An example would be the class of Atomic value holders, e.g. AtomicReference.
Because, the way you described it, in this case, they are not using ExampleClass.this.obj, they are calling the method ExampleClass.this.obj().
ExampleClass.this refers to the encapsulating instance of ExampleClass in which this ClassA instance is instantiated.
Not necessarily.
精彩评论