java_闭包和回调实现一边按键盘一边演讲

时间:2022-11-29 00:34:10
package ming;

interface Teachable {
void work();
}

class Programer {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Programer() {
}

public Programer(String name) {
this.name = name;
}

public void work() {
System.out.println(name + " 正在敲键盘");
}
}

class TeachableProgramer extends Programer {

public TeachableProgramer() {
}

public TeachableProgramer(String name) {
super(name);
}

private void teach() {
System.out.println(this.getName() + " 教师正在教学");
}
//内部类回调外部类实现work方法,内部类只是为了提供一个回调外部类的途径
private class Closure implements Teachable {

@Override
public void work() {
teach();
}

}
//非静态内部类引用允许外部类通过该非态内部类引用回调外部类方法
public Teachable getCallbackReference() {
return new Closure();
}

}
public class TestClosured {

public static void main(String[] args) {
// TODO Auto-generated method stub
TeachableProgramer tp = new TeachableProgramer("zhangsan");
tp.getCallbackReference().work();
tp.work();

}

}