javaoopfinalanonymous-inner-class

How am I able to access non-final variable from anonymous inner class?


I have 2 Java classes.

  1. TestLogging
  2. Test2

In both the classes I have written the same logic. But in TestLogging class, I am not allowed to access non-final variable in anonymous inner class.

But in Test2 class, why am I allowed to access non-final variable in anonymous inner class?

TestLogging

Test2

How is it possible to access non-final variable from anonymous inner class?


Solution

  • The difference is due to the version of the JDK against which you're compiling (or the target version).

    Java 8 understands "effectively final" variables. Where you compile with JDK 8, you do not have to explicitly declare the variable as final in order to reference it in the anonymous class.

    In other words, the variable s, although not declared as final, is not being reassigned, and that makes it "effectively final" (check this answer for more info).

    Before Java 8 (and your other project - TestLogging - has a target version of 1.5), variables had to be explicitly declared as final