我正在学习Java,我遇到了一个Closure的例子:
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();
}
}
interface Incrementable {
void increment();
}
class Callee1 implements Incrementable {
private int i = 0;
@Override
public void increment() {
i++;
print(i);
}
}
class MyIncrement {
public void increment() {
System.out.println("another operation");
}
public static void f(MyIncrement m) {
m.increment();
}
}
class Callee2 extends MyIncrement {
private int i = 0;
public void increment() {
super.increment();
i++;
print(i);
}
private class Closure implements Incrementable {
@Override
public void increment() {
Callee2.this.increment();
}
}
Incrementable getcallbackReference() {
return new Closure();
}
}
class Caller {
Incrementable callbackRegerence;
Caller(Incrementable cbh) {
callbackRegerence = cbh;
}
void go() {
callbackRegerence.increment();
}
}
示例作者的注释:
当myincrement被继承到Callee2时,increment()不能被Incrementable覆盖使用,所以你必须使用内部类提供一个单独的实现。
我的问题是:什么?为什么我们不能?我们在Callee2类中重写它还是我误解了作者?请解释一下他这句话想说什么。
您需要使用Incrementable类型作为Caller参数。您可以将其更改为相同的
旧
class Callee2 extends MyIncrement {
private int i = 0;
public void increment() {
super.increment();
i++;
print(i);
}
private class Closure implements Incrementable {
@Override
public void increment() {
Callee2.this.increment();
}
}
Incrementable getcallbackReference() {
return new Closure();
}
}
新:
class Callee2 extends MyIncrement implements Incrementable {
private int i = 0;
public void increment() {
super.increment();
i++;
System.out.println(i);
}
}