Inner class and local variables

NINCOMPOOP picture NINCOMPOOP · Apr 26, 2012 · Viewed 12.6k times · Source

Why do I need to declare a local variable as final if my Inner class defined within the method needs to use it ?

Example :

class MyOuter2 {

private String x = "Outer2";

void doStuff() {
    final String y = "Hello World";

    final class MyInner {

        String z = y;

        public void seeOuter() {
            System.out.println("Outer x is "+x);
            System.out.println("Local variable is "+y);
            MyInner mi = new MyInner();
            mi.seeOuter();
        }
    }
}

}

Why the String y needs to be a final constant ? How does it impact ?

Answer

mprabhat picture mprabhat · Apr 26, 2012

Local variables always live on the stack, the moment method is over all local variables are gone.

But your inner class objects might be on heap even after the method is over (Say an instance variable holds on to the reference), so in that case it cannot access your local variables since they are gone, unless you mark them as final