内部类向上转型为接口
public interface Destination {
String readLable();
}
public interface Contents {
int value();
}
public class Parcel {
private class PContents implements Contents{
private int i = 11;
@Override
public int value() {
return i;
}
}
protected class PDestination implements Destination{
private String lable;
private PDestination(String whereto) {
lable = whereto;
}
@Override
public String readLable() { return lable; }
}
public Destination dest(String s){
return new PDestination(s);
}
public Contents cont(){
return new PContents();
}
}
/**
* 1.内部类向上转型为接口可以完全隐藏内部类的具体实现过程
*
* 2.可以定义多个内部类 以不同的方式实现接口中的同一个方法
*
* 3.这种技巧经常被应用在swing编程中,可以在一个类中做出不同的响应事件。
* @author jack
*
*/
public class ParcelTest {
public static void main(String[] args) {
Parcel p = new Parcel();
Contents c = p.cont();
System.out.println(c.value());
Destination d = p.dest("Shanghai");
System.out.println(d.readLable());
}
}