日期:2014-05-20 浏览次数:20709 次
interface Teachable
{
void work();
}
class Programmer
{
private String name;
public Programmer(){}
public Programmer(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public void work()
{
System.out.println(name+"在灯下认真敲键盘...");
}
}
class TeachableProgrammer extends Programmer
{
public TeachableProgrammer()
{
}
public TeachableProgrammer(String name)
{
super(name);
}
public void teach()
{
System.out.println(getName()+"教室在讲台上认证讲课...");
}
//非静态内部类回调外部类实现work方法,非静态内部类引用的作用仅仅是向客户类提供一个回调外部类的途径
public class Closure implements Teachable
{
public void work()
{
teach();
}
public Teachable getCallbackReference() //返回一个非静态内部类引用,允许外部类通过该非静态内部类引用来回调外部类的方法
{
return new Closure();
}
}
}
//下面程序示范了如何让TeachableProgrammer对象既能执行教学的work方法,也能执行编程的work方法
public class TeachableProgrammerTest
{
public static void main(String[] args)
{
TeachableProgrammer tp=new TeachableProgrammer("李刚");
tp.work();
tp.getCallbackReference().work();
}
}