[Java] Warum können lokale Klassen nicht auf non-final Variablen zugreifen? *geklärt*

theHacker

sieht vor lauter Ads den Content nicht mehr
Teammitglied
ID: 69505
L
20 April 2006
22.682
1.316
Hierzu folgender Code:
PHP:
public class Dummy {
    
    public void foo(int localVar, final int finalVar) {
        class InnerMethodClass {
            public void foo() {
                int a = localVar; // <-- Fehler
                int b = finalVar;
            }
            
        }
    }
}


class Dummy2 {
    int objVar;
    final int classVar;
    
    class InnerClass {
        public void foo() {
            int a = objVar; // <-- OK
            int b = classVar;
        }
    }
}
Der Compiler liefert die folgende Fehlermeldung:
Dummy.java:6: local variable localVar is accessed from within inner class; needs to be declared final
int a = localVar;
Dass es so ist, klar, seh ich: Weitere Infos

Interessant finde ich die Frage, warum das final-Keyword gesetzt werden muss. Was unterscheidet jetzt eine lokale Klasse (innerhalb einer Methode) von einer inneren Klasse ?
 
The reason for this restriction becomes apparent from the implementation. A local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each local class constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee, the local class can be assured that its internal copies of the variables are always in sync with the real local variables.

https://www.unix.org.ua/orelly/java-ent/jnut/ch03_13.htm