Bird
Raised Fist0

If a class exposes a public getter but no setter for a private field, what is a likely reason an interviewer would probe this design choice?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Encapsulation - Data Hiding, Getters/Setters & Access Modifiers
If a class exposes a public getter but no setter for a private field, what is a likely reason an interviewer would probe this design choice?
ATo test if the candidate thinks public fields are better than getters
BTo confirm that the candidate knows getters always require setters
CTo verify that the candidate believes private fields should never be exposed
DTo check if the candidate understands immutability and controlled read-only access
Step-by-Step Solution
  1. Step 1: Understand getter-only design

    Getter without setter implies read-only access, often for immutability or controlled exposure.
  2. Step 2: Analyze interviewer intent

    Interviewer probes if candidate recognizes design for immutability or encapsulation control.
  3. Step 3: Evaluate incorrect options

    To confirm that the candidate knows getters always require setters is false; setters are not always required. To verify that the candidate believes private fields should never be exposed is extreme; exposing read-only data is common. To test if the candidate thinks public fields are better than getters is a misconception favoring public fields.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Getter-only design supports immutability and controlled access.
Quick Trick: Getter-only means read-only, not incomplete encapsulation [OK]
Common Mistakes:
MISTAKES
  • Assuming getters must have setters
  • Thinking private fields must never be exposed
  • Believing public fields are simpler and better
Trap Explanation:
PITFALL
  • Options A, B, and C reflect common but incorrect beliefs about encapsulation and access control.
Interviewer Note:
CONTEXT
  • Tests deep understanding of design choices for immutability and controlled access.
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