Bird
Raised Fist0

Given the following code snippet using the State pattern, what will be the output?

medium📝 Analysis Q4 of Q15
LLD - Behavioral Design Patterns — Part 1
Given the following code snippet using the State pattern, what will be the output?
class Context {
  State state;
  Context(State s) { state = s; }
  void request() { state.handle(this); }
}

class State {
  void handle(Context c) { System.out.println("State base"); }
}

class ConcreteStateA extends State {
  void handle(Context c) { System.out.println("State A"); }
}

Context ctx = new Context(new ConcreteStateA());
ctx.request();
AState A
BNo output
CCompilation error
DState base
Step-by-Step Solution
Solution:
  1. Step 1: Identify which handle method is called

    The Context's request method calls state.handle(this). The state is an instance of ConcreteStateA.
  2. Step 2: Determine output of ConcreteStateA's handle

    ConcreteStateA overrides handle to print "State A". So calling handle prints "State A".
  3. Final Answer:

    State A -> Option A
  4. Quick Check:

    ConcreteStateA handle() prints "State A" [OK]
Quick Trick: Overridden method in current state class runs [OK]
Common Mistakes:
MISTAKES
  • Assuming base class method runs
  • Expecting compilation error due to missing override
  • Thinking no output occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes