Bird
0
0

What is wrong with this Java Memento pattern snippet?

medium📝 Analysis Q7 of 15
LLD - Behavioral Design Patterns — Part 2
What is wrong with this Java Memento pattern snippet?
class Memento {
    private String state;
    public Memento(String state) { this.state = state; }
    public String getState() { return state; }
}

class Originator {
    private String state;
    public void setState(String state) { this.state = state; }
    public Memento save() { return new Memento(state); }
    public void restore(Memento m) { this.state = m.state; }
}
AMemento constructor is missing
BCannot access private field 'state' directly in restore method
COriginator's setState method is incorrect
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check access modifiers and usage

    Memento's 'state' field is private, so direct access m.state in Originator is illegal.
  2. Step 2: Identify correct access method

    Originator should use m.getState() to access the state value.
  3. Final Answer:

    Cannot access private field 'state' directly in restore method -> Option B
  4. Quick Check:

    Private fields need getters for access [OK]
Quick Trick: Use getters to access private fields in Java [OK]
Common Mistakes:
MISTAKES
  • Accessing private fields directly
  • Ignoring encapsulation rules
  • Assuming constructor is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes