Bird
0
0

Identify the bug in this Java code using Template Method pattern:

medium📝 Analysis Q7 of 15
LLD - Behavioral Design Patterns — Part 1
Identify the bug in this Java code using Template Method pattern:
abstract class Worker {
    final void work() {
        startWork();
        doWork();
        endWork();
    }
    abstract void doWork();
    void startWork() { System.out.println("Starting work"); }
    void endWork() { System.out.println("Ending work"); }
}
class Employee extends Worker {
    void doWork(int hours) { System.out.println("Working " + hours + " hours"); }
}
AdoWork method in Employee does not override abstract method due to different signature
BMissing implementation of startWork() in Employee
Cwork() method should not be final
DendWork() method must be abstract
Step-by-Step Solution
Solution:
  1. Step 1: Check method overriding rules

    Abstract doWork() has no parameters; Employee's doWork(int) has parameter, so it overloads, not overrides.
  2. Step 2: Consequence of no override

    Employee does not implement abstract method doWork(), causing compilation error.
  3. Final Answer:

    doWork method in Employee does not override abstract method due to different signature -> Option A
  4. Quick Check:

    Method signature mismatch causes override failure = doWork method in Employee does not override abstract method due to different signature [OK]
Quick Trick: Method signatures must match exactly to override [OK]
Common Mistakes:
MISTAKES
  • Assuming overloading equals overriding
  • Thinking startWork() must be overridden
  • Believing final method can be overridden

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes