模块之间只通过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:
- 子类的访问权限不能低于父类
- 不能为了测试, 而将类/接口变成API,可以将测试和类定义在同一个包中,访问protected元素
- 类中不允许有 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的引用对象都是不可变的。