What are captured variables in Java Local Classes

前端 未结 3 962
慢半拍i
慢半拍i 2020-12-05 11:32

The Java documentation for Local Classes says that:

In addition, a local class has access to local variables. However, a local class can only access

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 11:33

    Here is a post describing it: http://www.devcodenote.com/2015/04/variable-capture-in-java.html

    Here is a snippet from the post:

    ”It is imposed as a mandate by Java that if an inner class defined within a method references a local variable of that method, that local variable should be defined as final.”

    This is because the function may complete execution and get removed from the process stack, with all the variables destroyed but it may be the case that objects of the inner class are still on the heap referencing a particular local variable of that function. To counter this, Java makes a copy of the local variable and gives that as a reference to the inner class. To maintain consistency between the 2 copies, the local variable is mandated to be “final” and non-modifiable.

提交回复
热议问题