Original address: Https://sylvanassun.github.io/2017/07/30/2017-07-30-JavaClosure/
1. Free variables:
function Add (y) { returnfunction(x) { return x + y; }}
For intrinsic functions function(x) , y it is 自由变量 . instead y Add(y) of the parameters within the function, Add(y) a closure is formed on the inner function function(x) .
JavaUnlike JavaScript other languages that support closures, it is a class-based object-oriented language, meaning that a method always uses an 自由变量 instance of its own class.
class addutils { privateint y = 5; Public int Add (int x) { + y; }}
Such a method add(x) has a parameter x with one 自由变量y , and its return value is also dependent on this 自由变量y . add(x) If you want to work properly, you must rely on AddUtils an instance of the class, otherwise it will not know what 自由变量y the value is, that is, 自由变量 not add(x) bound with.
2. Strictly speaking, add(x) 自由变量 it should be this because it is y also this accessed through keywords.
Capture strategy in 3.Java is captured by value
- Capture-by-value: Simply copy the captured value to the object where you created the closure.
Java Both the anonymous inner class and the Java 8 new lambda expression are implemented in this way.
- Capture-by-reference: The captured local variable "lifted" (hoist) into the object.
C# The anonymous function (an anonymous delegate/LAMBDA expression) is implemented in this way.
4. Anonymous inner class is the embodiment of the closure in Java
Public InterfaceAnoninner () {intadd ();} Public classOuter { PublicAnoninner Getanoninner (Final intx) {Final inty = 5; return NewAnoninner () { Public intAdd () {returnX +y; } } }}
getAnonInner(x)The method returns an anonymous inner class AnonInner that does not explicitly declare the constructor, cannot pass arguments to the constructor, and returns an AnonInner interface, but add() uses two (and) in its method implementation, which means that the 自由变量 x y external method getAnonInner(x)this anonymous inner class constitutes a closure.
Closures in Java