内部类_为什么需要内部类
1.闭包与回调
当需要类似c语言的指针操作,返回一个指针时,Java内部类的闭包操作可以实现类似功能,且更为安全。
代码敲完,实现通过内部闭包类,实现类似指针的回调功能。
interface Incrementable {//接口
void increment();//“增长”
}
//第一个被调用的类,采用直接实现接口
class Callee1 implements Incrementable {
private int i = 0;
//实现接口的方法
public void increment() {
i++;
System.out.println("c1 i: " + i);
}
}
//先写个自己的基类
class MyIncrement {
public void increment() {
System.out.println("其他操作");
}
//写个供外面调用的方法
static void f (MyIncrement mi) {
//mi可能是该类的对象或者是子类的实例,子类实例的话调用的increment是子类的实现方法
mi.increment();
}
}
//第二个被调用的类,采用继承
class Callee2 extends MyIncrement {
private int i = 0;
public void increment() {
//先用super执行一次父类的increment()
super.increment();
i++;
System.out.println(i);
}
//增加一个内部类,闭包类
private class Closure implements Incrementable {
public void increment() {
//调用外围类的方法
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);
// output:
// 其他操作
// 1
Caller caller1 = new Caller(c1);
//Callee2由于没有直接实现接口,要通过拿到闭包的回调对象的引用
Caller caller2 = new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
// output:
// c1 i: 1
// c1 i: 2
caller2.go();
caller2.go();
// output:
// 其他操作
// 2
// 其他操作
// 3
}
}