What does a variable being “effectively final” mea

2019-01-15 06:25发布

This question already has an answer here:

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?

2条回答
时光不老,我们不散
2楼-- · 2019-01-15 06:52

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-15 07:02

According to the docs:

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

查看更多
登录 后发表回答