内部类调用问题

littlely_ll 2017-08-24 09:35:10

interface Incrementable{
void increment();
}
class Callee1 implements Incrementable{
private int i = 0;
public void increment(){
i++;
System.out.println(i);
}
}
class MyIncrement{
public void increment(){System.out.println("Other operation");}
static void f(MyIncrement mi){mi.increment();}
}
class Callee2 extends MyIncrement{
private int i = 0;
public void increment(){
super.increment();
i++;
System.out.println(i);
}
private class Closure implements Incrementable{
public void increment(){
//Specify outer-class method, otherwise you'll get an infinite recursion:
Callee2.this.increment();
}
}
Incrementable getCallbackReference(){
return new Closure();
}
}
class Caller{
private Incrementable callbackReference;
Caller(Incrementable cbh){callbackReference = cbh;}
void go(){callbackReference.increment();}
}
public class Callbacks{
public static void main(String [] args){
Callee1 c1 = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c2);
Caller caller1 = new Caller(c1);
Caller caller2 = new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
}


出现的结果为:
Other operation
1
1
2
Other operation
2
Other operation
3
倒数第三个和倒数第1个输出不是为1和2吗,为什么是2和3
...全文
151 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
soton_dolphin 2017-08-24
  • 打赏
  • 举报
回复
你在调用 MyIncrement.f(c2); 的时候已经让c2的属性i 变成1 了啊
littlely_ll 2017-08-24
  • 打赏
  • 举报
回复
谢谢,原来没看到

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧