当蒋内部类向上转型为其基类,尤其是转型为一个接口的时候,内部类就有了用武之地。
interface Contents{
int value();
}
interface Destination{
String readLabel();
}
class Parcel4 {
private class PContents implements Contents {
private int i = 11;
public int value() { return i; }
}
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
}
public PDestination destination(String s) {
return new PDestination(s);
}
public PContents contents() {
return new PContents();
}
}
public class Parcel {
public static void main(String[] args) {
Parcel4 p = new Parcel4();
Contents c = p.contents();//这里直接向上转型了
//! Parcel4.PContents pp = p.contents(); //新添加了一行,不能向下转型成private内部类,因为不能访问其名字,那么只能通过一种途径,那就是向上转型
Parcel4.PDestination pd = p.destination("Tasmania");//不能向下转型为protected是要在不同包内才能实现的,除非继承自它的子类。这里就不写了
// Illegal -- can't access private class:
}
} ///:~