Bird
Raised Fist0

Given a private field with a public getter but no setter, what happens if external code attempts to assign a new value directly to the field?

medium🧾 Trace Q4 of Q15
OOP & Design Patterns - Encapsulation - Data Hiding, Getters/Setters & Access Modifiers
Given a private field with a public getter but no setter, what happens if external code attempts to assign a new value directly to the field?
AThe getter method updates the field automatically
BThe field value changes successfully
CCompilation error due to inaccessible private field
DThe program throws a runtime exception
Step-by-Step Solution
Solution:
  1. Step 1: Access level of field

    The field is private, so direct access from outside is disallowed.
  2. Step 2: Effect of no setter

    Without a setter, external code cannot modify the field.
  3. Step 3: Result of direct assignment

    Attempting direct assignment causes a compilation error.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Private fields cannot be assigned externally [OK]
Quick Trick: Private fields block direct external assignment [OK]
Common Mistakes:
MISTAKES
  • Assuming getters allow modification
  • Thinking runtime exceptions occur instead of compile errors
  • Believing fields become public without setters
Trap Explanation:
PITFALL
  • Confusing getters with setters leads to wrong assumptions about mutability.
Interviewer Note:
CONTEXT
  • Tests knowledge of access control and immutability via encapsulation.
Master "Encapsulation - Data Hiding, Getters/Setters & Access Modifiers" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes