内部类与向上转型

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

 

 
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:
  }
} ///:~

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值