0

Why Local Inner class requires local variable Final? This Variable is in same method in which Local Inner class define. If we do not use final keyword then it will give compilation error. Please check the following program on ideone

class LocalInnerClassTest2 {
    private String x="Outer2";
    public static void main(String [] args){
        LocalInnerClassTest2 test=new LocalInnerClassTest2();
        test.doStuff();
    }
    void doStuff(){

//Why following local variable "final String z" requires final keyword

    final String z="local variable";
    class MyInner {
        public void seeOuter(){
            System.out.println("Outer x is "+x);
            System.out.println("Local variable z is "+z);
        }
    }
    MyInner my=new MyInner();
    my.seeOuter();
}
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
Neelabh Singh
  • 2,600
  • 12
  • 51
  • 88

1 Answers1

1

Because an inner class gets a copy of the environment which is available to it when it is instantiated.

If you don't declare z as final you could have a situation like the following:

  String z = "variable";

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

  z = "another value";

  my.seeOuter();

But the context for MyInner is created upon instantiation, so this would lead to seeOuter accessing a different value of z (bound before it is changed) and this would be misleading (and wrong since you wouldn't expect it).

Jack
  • 131,802
  • 30
  • 241
  • 343