当前位置: 首页 > Thinking in Java > 正文
第10章–内部类_ 向上转型 _隐藏细节
Jul112013
作者:边城网事 发布:2013-07-11 14:22 分类:Thinking in Java 阅读:1,152 抢沙发
public interface Destination { String readLabel(); }
public interface Contents { int value(); }
/** * * 内部类与 向上转型 * 改实例本质: * 1.使用内部类实现接口,该内部类是private 或者 * 内部类的 构造函数是private的,这样内部类只能在期外围内中使用,能够很好的隐藏细节 * 2.用外围类的一个方法返回接口类型,方法体中,返回的是实现该接口的内部类的实例,有个向上转型 * */ class Parcel4 { private class PContents implements Contents { private int i = 11; public int value() { return i; } } //尽管这个内部类是protected的,但是在它的外围内的子类中依然不能使用, //因为内部类的构造函数是private的. protected class PDestination implements Destination { private String label; private PDestination(String whereTo) //构造方法是private的 { label = whereTo; } public String readLabel() { return label; } } //2.用外围类的一个方法返回接口类型,方法体中,返回的是实现该接口的内部类的实例,有个向上转型 public Destination destination(String s) { return new PDestination(s); //调用内部类的 private构造方法? } 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(); //Parcel4.PDestination pp = p.new PDestination("ss"); } }
赞 赏
微信赞赏
支付宝赞赏
本文固定链接: https://www.jack-yin.com/coding/thinking-in-java/2372.html | 边城网事