Exams Knowledge Hub

MCQs for Competitive Exams, School & College Exams

Module: | Classes, Objects, OOPs & Inheritance

Q26: Consider the following statements regarding Encapsulation and Data Hiding in Java:

1. Encapsulation is fundamentally achieved by declaring instance variables as private to restrict direct external access from unauthorized classes.
2. The primary architectural purpose of getter and setter methods is to provide a controlled, validated gateway for accessing and modifying encapsulated private data.
3. Encapsulation strictly forbids a class from possessing read-only variables; a setter method must be universally provided for every single getter method defined in the class.

Which of the above statements is/are correct?
A
Only 1 and 2
B
Only 1 and 3
C
Only 2 and 3
D
1, 2, and 3
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because a developer can easily create a read-only variable by providing a getter method without a corresponding setter method.
Concept Definition: Encapsulation is the object-oriented principle of bundling data (variables) and the methods that operate on that data into a single, cohesive unit (a class), while simultaneously hiding the internal implementation details.
Structural Breakdown: The standard implementation involves marking all class attributes as 'private' (Data Hiding) and exposing 'public' accessor (getter) and mutator (setter) methods to safely interact with those attributes.
Historical/Related Context: Before encapsulation became an industry standard, legacy codebases heavily relied on public global variables.
If a variable like 'accountBalance' was public, any external code could maliciously or accidentally set it to a negative number.
Encapsulation prevents this by forcing all updates through a setter method where validation logic (e.g., if amount \> 0) can intercept the request.
Causal Reasoning: By completely decoupling the internal data structure from the external public API, developers can change the underlying data type of a private variable in the future without breaking any external software that relies on the established public getter methods.