Which three statements are benefits of encapsulation?
A. Allows a class implementation to change without changing the clients
B. Protects confidential data from leaking out of the objects
C. Prevents code from causing exceptions
D. Enables the class implementation to protect its invariants
E. Permits classes to be combined into the same package
F. Enables multiple instances of the same class to be created safely
题解
选项 A,经过封装过的类别可以保持 API 接口的一致,就算内部的程序实作有异动,也不需要去更改到其它引用了这个封装好的类别的程序。举例来说,某应用程序使用了其它封装成 JAR 文件的函数库来进行图像处理的计算,而这个函数库后来又有推出新版本来优化计算的速度。此时若要更新这个应用程序,让它去使用新版本的函数库的话,只需要替换 JAR 文件即可,不用更改或是重新编译原先的应用程序。
选项 B,封装可以隐藏代码,保护机密的数据外泄。
选项 C,封装无法防止例外的发生。
选项 D,封装可以让类别保护其不变条件(invariant),也就是让对象的状态永远符合规定的条件。
选项 E,封装观念和套件并没有直接的关系。
选项 F,封装与将一个类别实体化出不同对象的安全性并没有关联。
