What does a variable being “effectively final” mean? [duplicate]

眉间皱痕 提交于 2019-12-17 16:32:55

问题


The documentation on Anonymous Classes states

An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

I don't understand what does a variable being "effective final" mean. Can someone provide an example to help me understand what that means?


回答1:


Effectively final means that it is never changed after getting the initial value.

A simple example:

public void myMethod() {
    int a = 1;
    System.out.println("My effectively final variable has value: " + a);
}

Here, a is not declared final, but it is considered effectively final since it is never changed.

Starting with Java 8, this can be used in the following way:

public void myMethod() {
    int a = 1;
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("My effectively final variable has value: " + a);
        }
    };
}

In Java 7 and earlier versions, a had to be declared final to be able to be used in an local class like this, but from Java 8 it is enough that it is effectively final.




回答2:


According to the docs:

A variable or parameter whose value is never changed after it is initialized is effectively final.



来源:https://stackoverflow.com/questions/21473568/what-does-a-variable-being-effectively-final-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!