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 1787
囚心锁ツ
囚心锁ツ 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:34

    The reason is that Java doesn't support closures. There are no JVM commands to access local variable from outside the method, whereas fields of class can be easily accessed from any place.

    So, when you use final local variable in an inner class, compiler actually passes a value of that variable into constructor of the inner class. Obviously, it won't work for non-final variables, since they value can change after construction of the inner class.

    Fields of containing class don't have this problem, because compiler implicitly passes a reference to the containing class into the constructor of the inner class, thus you can access its fields in a normal way, as you access fields of any other class.

提交回复
热议问题