I have noticed in the code in my system that someone instantiated an anonymous class as follows
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 instances?
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?)
finalwhen you capture the variable of a local variable… not an instance variable of the enclosing class.ExampleClass.thisis a reference to the instance ofExampleClassassociated with the instance of the subclass ofClassA. In your case, it will be the same asthiswithinmethodA.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.