How does marking a variable as final allow inner classes to access them?

后端 未结 6 1089
天涯浪人
天涯浪人 2020-12-06 00:49

An inner class defined inside a method cannot access the method\'s local variables unless these local variables are marked final.I\'ve looked a

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 01:10

    The story behind this is that the creators of java didn't have enough time to make full support of closure.

    There are several ways to make the language support closure. For example, in scheme, the free parameters in a function are bound to an environment which corresponds to the lexical scope where the function is defined. In a language which forces immutable data such as SML, closure can be implemented by copying the local variables which are needed by the closure to the heap.

    So they create inner class to have a poor man's version of closure which mimics the style of ML.

提交回复
热议问题