java为什么匿名内部类的参数引用时final?

java为什么匿名内部类的参数引用时final 反而会报错?在《JAVA编程思想》书中看到的 不是很清楚 看得迷迷糊糊 的
关注者
500
被浏览
183,651
登录后你可以
不限量看优质回答私信答主深度交流精彩内容一键收藏

java8只是对‘事实上final’变量可以不声明final标识符而已,其实还是要求final,

Accessing Members of an Enclosing Class

A local class has access to the members of its enclosing class. In the previous example, the PhoneNumber constructor accesses the member LocalClassExample.regularExpression.

In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, itcaptures that variable or parameter. For example, the PhoneNumber constructor can access the local variable numberLength because it is declared final; numberLength is a captured variable.

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. For example, suppose that the variable numberLength is not declared final, and you add the highlighted assignment statement in the PhoneNumber constructor:

Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters. For example, you can define the following method in the PhoneNumber local class:

The method printOriginalNumbers accesses the parameters phoneNumber1 and phoneNumber2 of the method validatePhoneNumber.