1Z0-803 · Question #196
Which two actions will improve the encapsulation of a class?
The correct answer is A. Changing the access modifier of a field from public to private D. Returning a copy of the contents of an array or ArrayList instead of a direct reference. Encapsulation improves by restricting direct external access to internal data and ensuring controlled manipulation of an object's state.
Question
Which two actions will improve the encapsulation of a class?
Options
- AChanging the access modifier of a field from public to private
- BRemoving the public modifier from a class declaration
- CChanging the return type of a method to void
- DReturning a copy of the contents of an array or ArrayList instead of a direct reference
How the community answered
(39 responses)- A90% (35)
- B8% (3)
- C3% (1)
Why each option
Encapsulation improves by restricting direct external access to internal data and ensuring controlled manipulation of an object's state.
Changing a field's access modifier from public to private restricts direct external access, forcing consumers to interact with the field through controlled methods (getters/setters), thereby protecting the internal state from unintended modifications.
Removing the public modifier from a class makes it package-private, limiting its visibility but not directly improving the encapsulation of its internal fields or methods from other classes within the same package.
Changing a method's return type to void only signifies that the method does not return a value; it does not inherently restrict access to internal data or control state modifications, thus not directly improving encapsulation.
Returning a copy of an internal mutable collection prevents external code from directly modifying the object's internal data structure, ensuring that any changes made externally do not affect the object's encapsulated state without its explicit control.
Concept tested: OOP Encapsulation and Access Control
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Topics
Community Discussion
No community discussion yet for this question.