0

What is the internal reason due to which within method local inner class we can only access final or effectively final local variables of the method in which that inner class is declared? Please see below example.

class Test{
    int i = 10;
    static int j = 20;
    public void m1(){
        int k = 30;
        //k=40;
        final int m = 40;
        class Inner{
            public void m2(){
                System.out.println("value of i = " + i + " value of j = " + j + " value of k = " + k + " value of m = " + m);
            }
        }
        Inner i = new Inner();
        i.m2();
    }
    public static void main(String[] args){
        Test t = new Test();
        t.m1();
    }
}

If I try to change the value of variable k (line commented in source code), then there will be compiler error stating "local variables referenced from an inner class must be final or effectively final" Also in java versions lower than 1.8, local variables must be explicitly defined as final if you want to access that variable within method local inner class.

raven03
  • 89
  • 6
  • check [this out](https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class?rq=1), it covers this point too. – Curiosa Globunznik Oct 13 '19 at 09:54
  • @curiosa Thanks for the link. `The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope` I believe this is what related to my question from the link you have shared. Could you please share some sample code so I can understand this use-case? Thanks much – raven03 Oct 13 '19 at 10:06
  • can someone respond please?? – raven03 Oct 13 '19 at 12:57
  • You can take a look at the explanation in the [Java 8 tutorial](https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html). – kidney Oct 13 '19 at 13:46
  • Or, probably even better [here](http://cs-fundamentals.com/java-programming/java-method-local-inner-classes.php#scope-and-use-of-local-inner-classes) – kidney Oct 13 '19 at 13:49

0 Answers0