Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 392
Aniket Thakur Avatar asked Jan 31 '14 06:01

Aniket Thakur


People also ask

What is an effectively final variable?

An effectively final variable is one whose value doesn't change after it's first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.

What does effectively final mean?

In simple terms, objects or primitive values are effectively final if we do not change their values after initialization. In the case of objects, if we do not change the reference of an object, then it is effectively final — even if a change occurs in the state of the referenced object.

Why the variables used in Lambda body should be final or effectively final?

Forcing the variable to be final avoids giving the impression that incrementing start inside the lambda could actually modify the start method parameter.


2 Answers

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.

like image 92
Keppil Avatar answered Sep 30 '22 15:09

Keppil


According to the docs:

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

like image 42
Kick Avatar answered Sep 30 '22 16:09

Kick