內部類向上轉型爲接口

內部類向上轉型爲接口


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是私有的,不能被創建
    }

}
發佈了33 篇原創文章 · 獲贊 23 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章