知识大全 Java中的闭包与回调
Posted 知
篇首语:大鹏一日同风起,扶摇直上九万里。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 Java中的闭包与回调相关的知识,希望对你有一定的参考价值。
Java中的闭包与回调 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
闭包是一个可调用的对象 它记录了一些信息 这些信息来自于创建他的作用域 用过这个定义 可以看出内部类是面向对象的闭包 因为他不仅包含外围类对象的信息 还自动拥有一个指向此外围类对象的引用 在此作用域内 内部类有权操作所有的成员 包括private成员
Java代码
interface Incrementable
void increment();
class Callee implements Incrementable
private int i= ;
public void increment()
i++;
System out println(i);
class MyIncrement
void increment()
System out println( other increment );
static void f(MyIncrement mi)
mi increment();
class Callee extends MyIncrement
private int i= ;
private void incr()
i++;
System out println(i);
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 increment();//调用increment()方法
public class Callbacks
public static void main(String [] args)
Callee c =new Callee ();
Callee c =new Callee ();
MyIncrement f(c );
Caller caller =new Caller(c );
Caller caller =new Caller(c getCallbackReference());//将内部类中的Closure赋给Caller
caller go();
caller go();
caller go();
caller go();
输出
other increment
Callee 继承字MyIncrement 后者已经有一个不同的increment()方法并且与Incrementable接口期望的increment()方法完全不相关 所以如果Callee 继承了MyIncrement 就不能为了Incrementable的用途而覆蓋increment()方法 于是这能使用内部类独立的实现Incrementable
cha138/Article/program/Java/hx/201311/25624相关参考