内部类向上转型为接口

内部类向上转型为接口


public interface Destination {
    String readLable();
}
public interface Contents {
    int value();
}
public class Parcel {
    //普通的(非内部类),不能声明为private或protected,只能被赋予public或包访问权限
    private class PContents implements Contents{//私有,除了Parcel没有人能访问
        private int i = 11;
        @Override
        public int value() {
            return i;
        }

    }

   //protected 只有parcel及其子类,同一包中的类才能访问
   protected class PDestination implements Destination{
    private String lable;

    private  PDestination(String whereto) {
        lable = whereto;
    }

    @Override
    public String readLable() { return lable; }

   }    

   public Destination dest(String s){
    return new PDestination(s);
   }

   public Contents cont(){
    return new PContents();
   }


}
/**
 * 1.内部类向上转型为接口可以完全隐藏内部类的具体实现过程
 *
 * 2.可以定义多个内部类 以不同的方式实现接口中的同一个方法
 * 
 * 3.这种技巧经常被应用在swing编程中,可以在一个类中做出不同的响应事件。
 * @author jack
 *
 */

public class ParcelTest {

    public static void main(String[] args) {
        Parcel p = new Parcel();

        Contents c = p.cont();//upcasting 内部类向上转型为接口
        System.out.println(c.value());

        Destination d = p.dest("Shanghai");
        System.out.println(d.readLable());

        //PDestination pd = 
        //Parcel.PCcontents pc = p.new PContents();PContents是私有的,不能被创建
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值