内部类与向上转型

来源:互联网 发布:穿越火线fps优化器 编辑:程序博客网 时间:2024/06/05 09:13

当蒋内部类向上转型为其基类,尤其是转型为一个接口的时候,内部类就有了用武之地。

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");    // Illegal -- can't access private class:  }} ///:~


原创粉丝点击