Difference between final and effectively final

后端 未结 14 2836
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:38

I\'m playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know tha

14条回答
  •  旧时难觅i
    2020-11-22 01:08

    If you could add the final modifier to a local variable, it was effectively final.

    Lambda expressions can access

    • static variables,

    • instance variables,

    • effectively final method parameters, and

    • effectively final local variables.

    Source: OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide, Jeanne Boyarsky, Scott Selikoff

    Additionally,

    An effectively final variable is a variable whose value is never changed, but it isn’t declared with the final keyword.

    Source: Starting Out with Java: From Control Structures through Objects (6th Edition), Tony Gaddis

    Furthermore, don't forget the meaning of final that it is initialized exactly once before it is used for the first time.

提交回复
热议问题