Java MCQs – Encapsulation and abstraction

21.) Which access modifier allows a class member to be accessible within the same package and by subclasses outside the package?

A) private
B) default
C) protected
D) public

Answer: Option C

Explanation: The “protected” access modifier allows a class member to be accessed within the same package and by subclasses outside the package.

22.) In Java, what is the role of getters and setters in encapsulation?

A) Getters and setters are used to expose all internal attributes of a class.
B) Getters and setters allow direct access to attributes without restrictions.
C) Getters and setters provide controlled access to attributes while enforcing validation and encapsulation.
D) Getters and setters are used for constructor initialization.

Answer: Option C

Explanation: Getters and setters allow controlled access to attributes, enabling validation and encapsulation by applying logic before setting or retrieving values.

23.) How does encapsulation contribute to code reusability in Java?

A) By allowing direct modification of attributes
B) By preventing access to class members
C) By promoting the inheritance of private methods
D) By providing controlled methods for attribute access and modification

Answer: Option D

Explanation: Encapsulation provides controlled methods (getters and setters) for accessing and modifying attributes, allowing consistent and reusable ways to interact with the class.