內部類向上轉型爲接口
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());
}
}