目录
10.6 匿名内部类
Parcel7
interface Contents {
int value();
}
class Parcel7 {
public Contents contents() {
//(1)实现接口Contents的匿名内部类
return new Contents() {
@Override
public int value() {
System.out.println("Contents value!");
return 0;
}
};
}
public static void chapter10_6() {
Parcel7 parcel7 = new Parcel7();
//(2)子类向上转型为Contents接口
Contents contents = parcel7.contents();
//(3)多态,运行时执行匿名内部类的value函数
contents.value();
}
};
输出:
Contents value!
实现接口的匿名内部类
Parcel8
class Wrapping {
private int i;
public Wrapping(int x) {
i = x;
}
public int value() {
System.out.println("Wrapping i:" + i);
return i;
}
}
class Parcel8 {
public Wrapping wrapping(int x) {
// 继承基类的匿名内部类
return new Wrapping(x) {
public int value() {
return super.value();
}
};
}
public static void chapter10_6() {
Parcel8 parcel8 = new Parcel8();
Wrapping wrapping = parcel8.wrapping(7);
wrapping.value();
}
}
输出:
Wrapping i:7
继承基类的匿名内部类
10.8 闭包与回调
闭包(closure)是一个可调用对象。
内部类是面向对象的闭包,它自动拥有一个指向外围类对象的引用(.this)。在此作用域内,内部类有权操作所有成员,包括private成员。
人们认为Java应该包含某种类似指针的机制,以允许回调,通过内部类提供闭包的功能是优良的解决方案。
Callbacks
// 回调接口
interface Incrementable {
void increment();
}
// (1)Callee1使用接口实现回调
class Callee1 implements Incrementable {
private int i = 0;
@Override
public void increment() {
i++;
System.out.println("Callee1 i:" + i);
}
}
// (2)Callee2使用匿名内部类实现回调
class MyIncrementable {
public void increment() {
System.out.println("MyIncrementable");
}
}
class Callee2 extends MyIncrementable {
private int i = 7;
public void increment() {
super.increment();
i+=3;
System.out.println("Callee2 i:" + i);
}
// 匿名内部类
// 内部类是面向对象的闭包,它自动拥有一个指向外围类对象的引用(.this)
Incrementable callback() {
return new Incrementable() {
@Override
public void increment() {
Callee2.this.increment();
}
};
}
}
// 回调类
class Caller {
private Incrementable callback;
Caller(Incrementable call) {
callback = call;
}
void run() {
callback.increment();
}
}
class Callbacks {
public static void chapter10_8() {
Callee1 callee1 = new Callee1();
// (1)注册接口回调
Caller caller1 = new Caller(callee1);
// (1)调用回调
caller1.run();
Callee2 callee2 = new Callee2();
// (2)注册内部类回调
Caller caller2 = new Caller(callee2.callback());
// (2)调用回调
caller2.run();
}
}
输出:
Callee1 i:1
MyIncrementable
Callee2 i:10
(1)使用接口实现回调
(2)使用内部类实现回调