0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ALTAF
  • 41
  • 11
  • Side note: Consider using a lambda expression to minimize your code. See https://stackoverflow.com/questions/31416784/thread-with-lambda-expression – faris Oct 11 '18 at 05:20
  • Is this one of those trick questions where there is something hiding below screen view that makes everything somehow work out? Your Test2 class is quite long. – SynchroDynamic Oct 11 '18 at 05:21
  • Possible duplicate of [Difference between final and effectively final](https://stackoverflow.com/questions/20938095/difference-between-final-and-effectively-final) – Ori Marko Oct 11 '18 at 05:36
  • Please post your code as text, not as screenshots. – Mark Rotteveel Oct 12 '18 at 15:43

2 Answers2

4

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

ernest_k
  • 44,416
  • 5
  • 53
  • 99
2

Check maven configuration for java version enter image description here

Tsolak Barseghyan
  • 1,048
  • 11
  • 16