Bird
Raised Fist0

If an interviewer asks you to extend a class with private fields but no setters, how would you safely allow controlled modification of those fields in a subclass?

hard🎤 Interviewer Follow-up Q10 of Q15
OOP & Design Patterns - Encapsulation - Data Hiding, Getters/Setters & Access Modifiers
If an interviewer asks you to extend a class with private fields but no setters, how would you safely allow controlled modification of those fields in a subclass?
AChange the private fields to public in the superclass
BAdd protected or public setter methods in the superclass for controlled access
CDirectly access and modify private fields in the subclass using reflection
DDuplicate the fields in the subclass and manage them independently
Step-by-Step Solution
Solution:
  1. Step 1: Understand subclass access constraints

    Private fields are inaccessible; adding protected/public setters in superclass allows controlled subclass modification.
  2. Final Answer:

    Option B -> Option B
  3. Quick Check:

    Protected setters enable safe subclass access [OK]
Quick Trick: Use superclass setters for subclass access [OK]
Common Mistakes:
MISTAKES
  • Making fields public breaks encapsulation
  • Using reflection is unsafe and discouraged
  • Duplicating fields causes inconsistency
Trap Explanation:
PITFALL
  • Candidates may suggest unsafe or bad practices instead of proper accessor methods.
Interviewer Note:
CONTEXT
  • Tests deep understanding of encapsulation and inheritance interplay.
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