閉包是一個可調用的對象
Java代碼
interface Incrementable
{
void increment();
}
class Callee
{
private int i=
public void increment()
{
i++;
System
}
}
class MyIncrement
{
void increment()
{
System
}
static void f(MyIncrement mi)
{
mi
}
}
class Callee
{
private int i=
private void incr()
{
i++;
System
}
private class Closure implements Incrementable //內部類
{
public void increment()
{
incr();
}
}
Incrementable getCallbackReference()
{
return new Closure(); //新建內部類
}
}
class Caller
{
private Incrementable callbackRefference;
Caller(Incrementable cbh)
{
callbackRefference = cbh;
}
void go()
{
callbackRefference
}
}
public class Callbacks
{
public static void main(String [] args)
{
Callee
Callee
MyIncrement
Caller caller
Caller caller
caller
caller
caller
caller
}
}
輸出
other increment
Callee
內部類Closure實現了Incrementable 一提供一個放回Caller
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25624.html