1

Let us look at the following code (Let A be some simple class in the same package):

public class MyClass {
    public void outer() {
        int i=3;
        int j=i++;   // 1
        A a = new A() {
            int k = i++;   // 2
        };
    }
}

While the line 1 compiles without a problem, the line 2 generates the following compilation error:

Local variable i defined in an enclosing scope must be final or effectively

Assigning final to the variable i results in compilation error both in line 1 and in line 2 (which is reasonable since you cannot change a final variable).

What is the reason behind the compilation error in line 2?

This also happens in the next block of code:

public class MyClass {
    public void outer() {
        A[] arr = new A[10];
        for (int i=0 ; i<10 ; i++) {
            arr[i] = new A() {
                private int j = i; // 1
            };
        }
    }
}

resulting in the same compilation error in line 1. However, with the following changes in the code (at the marked lines 1 and 2) I get no compilation error:

public class MyClass {
    public void outer() {
        A[] arr = new A[10];
        for (int i=0 ; i<10 ; i++) {
            final int k = i; // 1
            arr[i] = new A() {
                private int j = k;  // 2
            };
        }
    }
}

I'm trying to get my head around the reasons behind this compilation choice, but I couldn't understand it all they way to the end. I'm guessing it has to do with possible changes the method will have on the variable but I'm not sure I understand it completely.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mickey
  • 1,405
  • 2
  • 13
  • 33

0 Answers0