I am still not satisfied with the explanation of the anonymous class and the final field. There were many questions that tried to explain the obvious problem, but I did not find the answers to all my questions :-)
Assume the following code:
public void method(final int i, int j) { final int z = 6; final int x = j; int k = 5; new Runnable() { public void run() { System.out.print(i); System.out.print(x); System.out.print(z); System.out.print(k); } }; }
- This code cannot be compiled due to the "unfinal"
k property. - I understand that the compiler can replace the
z property with a declared value at compile time.
When I was looking for a solution on how i and x can work, I found this answer that says:
Then the compiler can simply replace using lastPrice and price in an anonymous class with constant values โโ(at compile time, of course), and you will no longer have problems accessing non-existent variables
How can it work for fields i and x if they are method parameters? They are not known at compile time? This approach may work for z .
On the other hand, there is an explanation regarding stack issues :
This allows the Java compiler to "capture" the value of the variable at run time and store the copy as a field in the inner class. As soon as the external method completed and its stack stack was deleted, the original variable disappeared, but the internal private copy of the class is stored in the memory of its own class
I would understand that an anonymous class somehow copied all the necessary content (fields) during its creation. The absence of final has an obvious problem: if some code below the anonymous class declaration changes the value, then stale values โโare possible as a result of execution.
But this is normal, this should solve the problem when the method of the anonymous class is executed from the scope of the used properties.
But this approach should work even without a final declaration, since it just copies all the fields.
Both approaches seem independent to me. Speaking of which - and this may solve my questions - I have not found how the final method method works. They are not removed from the stack, even if the method exits? This seems nonsense to me, but it explains a lot of things :-)
What is the correct answer?