Chapter4 Item13 使类和成员的可访问性最小化

模块之间只通过API通信,其他的隐藏起来。
降低耦合,独立地开发,测试,优化

Access control

• private—The member is accessible only from the top-level class where it is declared.
• package-private—The member is accessible from any class in the package where it is declared. Technically known as default access, this is the access lev- el you get if no access modifier is specified.
• protected—The member is accessible from subclasses of the class where it is declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the package where it is declared.
• public—The member is accessible from anywhere.

ps:

  1. 子类的访问权限不能低于父类
  2. 不能为了测试, 而将类/接口变成API,可以将测试和类定义在同一个包中,访问protected元素
  3. 类中不允许有 public mutable/static fields, 但是final可以为public。final域全为大写字母,单词用下划线隔开。final域不可以是可变对象的引用,例如数组。所以类具有public static final的数组或者返回它的访问方法都是错误的。
    修改方案:
    (1)使public array变成private, 增加一个public immutable list:
private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
  Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

(2)使array变成private,定义一个public方法,访问array的备份:

  private static final Thing[] PRIVATE_VALUES = { ... };
   public static final Thing[] values() {
       return PRIVATE_VALUES.clone();
   }

summary

尽可能减少public数目,field除了final以外,都不能是public的。并且final的引用对象都是不可变的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,940评论 0 23
  • Chapters: Enumerations - Advanced Operators Excerpt From:...
    碧波浮沉阅读 680评论 0 1
  • 蓟州行 十月金秋,天清气爽,正是旅游的佳季。11、12号是国庆长假后的第一个双休日,学校组织班主任老师前往蓟县参观...
    开宗明义阅读 551评论 0 0
  • 近期谷歌浏览器宣布也不再支持flash插件,Hlml播放视频学习很有必要实例: 元素提供了 播放、暂停和音量控件来...
    小弱鸡阅读 611评论 0 1
  • 五月初始,清风拂面。 我喜欢风和你,蓝天;我听见风就是雨,而你笑就是美 ,灵雀。 我想起了你,把你揣到兜里 ,藏在...
    如知阅读 405评论 2 4