Bird
Raised Fist0

Identify the error in this Java Strategy pattern code snippet:

medium📝 Analysis Q6 of Q15
LLD - Behavioral Design Patterns — Part 1
Identify the error in this Java Strategy pattern code snippet:
interface Strategy { void execute(); }
class ConcreteStrategy implements Strategy {
public void execute() { System.out.println("Running"); }
}
class Context {
private Strategy strategy;
public Context() { }
public void setStrategy(Strategy s) { strategy = s; }
public void doWork() { strategy.execute(); }
}
Context c = new Context();
c.doWork();
AInterface method execute() is not implemented
BContext constructor should accept Strategy parameter
Cstrategy is never initialized before use, causing NullPointerException
DsetStrategy method should be static
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Context usage

    Context is created with default constructor, strategy is null initially.
  2. Step 2: Identify method call issue

    Calling doWork() calls strategy.execute(), but strategy is null, causing NullPointerException.
  3. Final Answer:

    strategy is never initialized before use, causing NullPointerException -> Option C
  4. Quick Check:

    Uninitialized strategy causes runtime error [OK]
Quick Trick: Always initialize strategy before calling execute [OK]
Common Mistakes:
MISTAKES
  • Ignoring null initialization
  • Thinking interface method missing
  • Assuming constructor must have parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes