内部类与向上转型,当蒋内部类向上转型为其基类,尤其是转型为一个接口的时候,内部类就有了用武之地。
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 Destination destination(String s) { return new PDestination(s); } public Contents contents() { return new PContents(); } } public class TestParcel { public static void main(String[] args) { Parcel4 p = new Parcel4(); Contents c = p.contents();//这里直接向上转型了 //!Parcel4.PContents pp = p.contents();新添加了一行,不能向下转型成private内部类,因为不能访问其名字,那么只能通过一种途径,那就是向上转型 //!protected跟这个差不多,我就不一一去试了 Destination d = p.destination("Tasmania"); // Illegal -- can't access private class: //! Parcel4.PContents pc = p.new PContents(); } } ///:~