Accessing Effectively Final Variables From Anonymous Inner Classes in Java 8

Before Java 8, you could only use final variables from a surrounding class in an anonymous inner class. In Java 8, within anonymous class (or lambda expressions) you can use effectively final variables: not declared as final but only assigned once. 


Important points about accessing variables from within an anonymous inner class (or lambda expression)

  1. If you don't assign any value and try to access it from within a lambda expression, you will get the older error that the variable might not have been initialized.

  2. You cannot reassign a local variable even after being used in the lambda expression. You will get error within the lambda expression where you actually use it.

  3. There is not restriction on the use of instance or static variables within a lambda expression or an anonynous inner class.



Add examples, before and after telling which line code will fail. For all cases.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within!!!