Which two actions will improve the encapsulation of a class?

A. Changing the access modifier of a field from public to private
B. Removing the public modifier from a class declaration
C. Changing the return type of a method to void
D. Returning a copy of the contents of an array or ArrayList instead of a direct reference

题解

选项 A,把字段用 private 修饰字来声明成私有成员,接着再使用 setter 和 getter 方法来提供给外部访问确实会比较符合封装的概念。

选项 B,为了要让类别可以被外部使用,还是需要公开的方法的。

选项 C,也要有可以回传数值或是对象的方法,不然类别的作用不大。

选项 D,拷贝一份新的数组对象可以避免封装内的数组对象里的内容在外部被改变。