频道栏目
首页 > 资讯 > 其他 > 正文

内部类与向上转型

17-06-28        来源:[db:作者]  
收藏   我要投稿

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

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();
  }
} ///:~
相关TAG标签
上一篇:用正则表达式进行复杂密码校验
下一篇:Python基础-分布式进程
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站