17

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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • 8
    http://stackoverflow.com/questions/20938095/difference-between-final-and-effectively-final - although I thought that being `final` was a requirement for local variable access from Java's pseudo-closures (but I'm wrong/outdated quite regularly) :-/ – user2864740 Jan 31 '14 at 06:13

2 Answers2

25

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.

Keppil
  • 45,603
  • 8
  • 97
  • 119
  • when we declare final keyword with variable compiler does not allow us to change the variable value, but according to effectively final, there is no need to declare final keyword with variable, so is it possible to change the value of effectively variable ? it means when we change the value, the variable not effectively final ? – Harmeet Singh Taara Apr 22 '14 at 18:13
  • @Harmeet: Indeed if you changed the value it would no longer be effectively final, so you can't change the value of an effectively final variable. – Keppil Apr 23 '14 at 04:18
5

According to the docs:

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

tom
  • 2,735
  • 21
  • 35
Kick
  • 4,823
  • 3
  • 22
  • 29