美文网首页
final 和effectively final区别

final 和effectively final区别

作者: ae12 | 来源:发表于2018-10-12 12:42 被阅读182次

在学习局部内部类(local inner class)时,遇到了effectively final 的说法。一时不知所云,就google了一下。下面是stackoverflow上的解答,看完,顿时豁然开朗,记载一下,供后来者查阅。

Difference between final and effectively final

其中一位回答,感觉很好:
... 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 marked assignment statement in the PhoneNumber constructor:

public class OutterClass {  

  int numberLength; // <== not *final*

  class PhoneNumber {

    PhoneNumber(String phoneNumber) {
        numberLength = 7;   // <== assignment to numberLength
        String currentNumber = phoneNumber.replaceAll(
            regularExpression, "");
        if (currentNumber.length() == numberLength)
            formattedPhoneNumber = currentNumber;
        else
            formattedPhoneNumber = null;
     }

  ...

  }

...

}

Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:

如果你给变量numberLength 又重新赋值了,则numberLength就不再是effectively final。java 编译出错 “local variables referenced from an inner class must be final or effectively final”

相关文章

网友评论

      本文标题:final 和effectively final区别

      本文链接:https://www.haomeiwen.com/subject/bcgwaftx.html