Why a non-final “local” variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?

前端 未结 4 1798
囚心锁ツ
囚心锁ツ 2020-11-30 20:36

There are some topics on Stack Overflow on the compiler error Cannot refer to a non-final variable message inside an inner class defined in a different method a

4条回答
  •  天涯浪人
    2020-11-30 21:24

    three types of things: instance variables, local variables,and objects:

    ■ Instance variables and objects live on the heap.
    ■ Local variables live on the stack.
    

    Inner class object cannot use the local variables of the method in which the local inner class is defined.

    because use local variables of the method is the local variables of the method are kept on the stack and lost as soon as the method ends.

    But even after the method ends, the local inner class object may still be alive on the heap. Method local inner class can still use the local variables that are marked final.

    final variable JVM takes these as a constant as they will not change after initiated . And when a inner class try to access them compiler create a copy of that variable into the heap and create a synthetic field inside the inner class so even when the method execution is over it is accessible because the inner class has it own copy.

    synthetic field are filed which actually doesn't exist in the source code but compiler create those fields in some inner classes to make those field accessible.

提交回复
热议问题