Question
Why does calling the 'recursive' method in class B result in an infinite loop when dealing with inheritance in Java?
class A {
void recursive(int i) {
System.out.println("A.recursive(" + i + ")");
if (i > 0) {
recursive(i - 1);
}
}
}
class B extends A {
void recursive(int i) {
System.out.println("B.recursive(" + i + ")");
super.recursive(i + 1);
}
}
public class Demo {
public static void main(String[] args) {
B b = new B();
b.recursive(10);
}
}
Answer
This issue arises due to the interplay between how methods are overridden and how recursion unfolds when using inheritance in Java. When the 'recursive' method in class B is called, it leads to unexpected behavior, resulting in an infinite loop instead of the anticipated countdown.
class A {
void recursive(int i) {
System.out.println("A.recursive(" + i + ")");
if (i > 0) {
recursive(i - 1);
}
}
}
class B extends A {
void recursive(int i) {
System.out.println("B.recursive(" + i + ")");
super.recursive(i - 1); // Changed to decrement
}
}
Causes
- Class B's recursive method calls super.recursive(i + 1), which in turn calls the recursive method in class A, passing an incremented value each time.
- Static nature of recursion doesn't account for the change in context when coming back from the superclass method, resulting in the same call in class B again and again.
- Since B's method increments the value before passing it to A's method, the base case for stopping (i > 0) is never met when calling super.recursive.
Solutions
- Change the recursive method in class B to call A's recursive method with a decreased value (i - 1) instead of incrementing it (i + 1). This will allow decrementing the value correctly through each recursive call.
- Use a different stopping condition in class B's recursive method to prevent it from endlessly calling class A, ensuring to align the logic correctly between both classes.
Common Mistakes
Mistake: Misunderstanding how method overriding affects recursion, especially with super calls.
Solution: Always verify the flow of recursion and what values are being passed between overridden methods.
Mistake: Not putting in place proper base cases for recursion in derived classes.
Solution: Ensure that the logic in derived classes doesn't unintentionally create conditions leading to infinite loops.
Helpers
- Java inheritance
- Java recursion
- infinite loop in Java
- method overriding Java
- Java super method
- Java recursion example