Page 1 of 1

About Question enthuware.ocpjp.v7.2.1501 :

Posted: Fri Feb 13, 2015 5:07 am
by Alina_Lapina
Hi, why automatic variables are not accessible for en inner class defined in a non-static method? Is it any logic back it? Thanks in advance.

Re: About Question enthuware.ocpjp.v7.2.1501 :

Posted: Fri Feb 13, 2015 6:45 am
by admin
I didn't see any special reasoning for it mentioned in the JLS. My guess is that it is because an object of the inner class may survive even after the method ends, while automatic variables are created on the stack, which is cleaned up after the method ends. So it is not really possible to have access to a variable that doesn't exist.

Actually, in Java 8, such variable are accessible in an inner class if they are "effectively final" i.e. if such variables never change after assigned a value. This is possible because now only the value needs to be preserved and not the actual variable.

HTH,
Paul.