-3

I am asking this , because final & non-final have same scope , so why VARIABLE are added as final variable in java .. & what is the affect of adding some variable as final , when it is only accessed under some scope .

public void game()
{
    final String str = "a" ;
        //String str ="a" ;

    class hollow 
    {
        public void game ()
        {
            System.out.println(str);
        }
    }
}
  • 2
    Please could you clarify your question! – devrobf Mar 05 '13 at 12:03
  • 1
    See [Cannot refer to a non-final variable inside an inner class defined in a different method](http://stackoverflow.com/q/1299837/851811), or [Why are only final variables accessible in anonymous class?](http://stackoverflow.com/q/4732544/851811). – Xavi López Mar 05 '13 at 12:05

1 Answers1

0

Final and inner classes http://en.wikipedia.org/wiki/Final_%28Java%29#Final_variables

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62