Referencing non-final variable: why does this code compile?

为君一笑 提交于 2019-12-03 09:29:49

I guess you are compiling with Java 8. Here your jtf variable is effectively final, so it compiles fine. A variable is effectively final if its value is never changed after you initialized it.

See also Local Classes:

However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

and

Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class

Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:

  • An anonymous class has access to the members of its enclosing class.

  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

[...]

If you tried with:

javac -source 1.7 MyFile.java

you'll have your expected error.

.java:13: error: local variable jtf is accessed from within inner class; needs to be declared final
                jtf.setText(evt.getLocationOnScreen().toString());
                ^
1 error

So the answer of the exam question is: it compiles only if you're using Java 8+.

John Kugelman supports Monica

Java 8 added the ability to access "effectively final" variables. The final keyword is no longer required as long as a variable is never changed after it is initialized.

It may work in Java8 as the stress is on Effectively Final which means once the value is assigned to jtf it should not be changed after wards. As per Java doc:

A variable or parameter whose value is never changed after it is initialized is effectively final.

Seems that your Eclipse IDE uses Java 7 compiler. To change this to Java 8 use Project->Properties->Java Compiler->Compiler compliance level.

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