Local class can access non-final variable in java 8

会有一股神秘感。 提交于 2019-11-27 06:38:07

问题


Before Java 8, We were not able to use non-final variables inside local class. But now they are allowing final as well as effectively final(who's values has not been changed), can be referred by local classes. What i know(Correct me if i am wrong), they didn't supported referring non-final values because there values can be changed. So, how they are supporting it now and why it was not supported earlier.


回答1:


The situation has not changed at all, actually. The compiler is just a bit smarter, and doesn't force you to use the final keyword anymore.

If it detects that the variable is effectively final, i.e. assigned only once, and never after, everything is good. If it detects that it's not effectively final, it refuses to compile.

So, instead of forcing you to make a variable final, it detects it automatically. But you still can't use non-effectively-final variables inside an inner class or lambda.



来源:https://stackoverflow.com/questions/23580826/local-class-can-access-non-final-variable-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!