java 内部类和向上转型

当将内部类向上转型为其基类时,尤其是转型为一个接口的时候,内部类就有了用武之地,(从实现某个接口的对象,得到对接口的引用,与向上转型为这个对象的基类,实际上是一样的效果,),这是因为此内部类---某个接口的实现---能够完全不可见,并且不可用,所得到的只是指向基类或接口的引用,所以能够很方便地隐藏实现细节

//: innerclasses/Destination.java
package object;
public interface Destination {
  String readLabel();
} ///:~
//: innerclasses/Contents.java
package object;
public interface Contents {
  int value();
} ///:~
//: innerclasses/TestParcel.java
package object;
class Parcel4 {
  private class PContents implements Contents { //private类除了直接外部类parcel4,没人可以访问
    private int i = 11;
    public int value() { return i; }
  }
  protected class PDestination implements Destination {//protect类只有直接外部类及其子类可以访问,还有同一个包的可以访问
    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();
    Destination d = p.destination("Tasmania");
    // Illegal -- can't access private class:
    //! Parcel4.PContents pc = p.new PContents();
  }
} ///:~

 

posted @ 2019-01-04 14:05  江期玉  阅读(514)  评论(0编辑  收藏  举报