'why is anonymous class able to access the local variable [closed]

public String doSomething(){
    int i=5;

    return TestEmploye.doStringstuff(new UpperConcat() { //no name of this class
        @Override
        public String upperAndConcat(String s1, String s2) {
            System.out.println(i);
            return s1.toUpperCase()+s2.toUpperCase();
        }
    },"hello ","vishnu");
}

I have read some documentation and stackiverflow article and as per them a local inner class(class within method) or anonymous class cannot access local variable but in the above code::::::::::::::::::

i have created an interface upperAndConcat with a single Method with two string arguements [public String upperAndConcat(String s1, String s2);] TestEmployee has static method doStringstudd which i called directly

Now the question is i have decalred int i=5 as local variable inside dosomething method how is the anonymous class able to access it ???????????????????????



Solution 1:[1]

Anonymous Classes, The JavaTM Tutorials:

  • An anonymous class cannot access local variables ... that are not declared as final or effectively final.

The variable i is not changed, so it is effectively final. For this reason it can be accessed by the anonymous class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oskar Grosser