title: Inheritance and recursion
body: <p>Suppose we have the following classes:</p>
  
  <pre><code>class A {
  
      void recursive(int i) {
          System.out.println("A.recursive(" + i + ")");
          if (i &gt; 0) {
              recursive(i - 1);
          }
      }
  
  }
  
  class B extends A {
  
      void recursive(int i) {
          System.out.println("B.recursive(" + i + ")");
          super.recursive(i + 1);
      }
  
  }
  </code></pre>
  
  <p>Now lets call <code>recursive</code> in class A:</p>
  
  <pre><code>public class Demo {
  
      public static void main(String[] args) {
          A a = new A();
          a.recursive(10);
      }
  
  }
  </code></pre>
  
  <p>The output is, as expected counting down from 10.   </p>
  
  <pre><code>A.recursive(10)
  A.recursive(9)
  A.recursive(8)
  A.recursive(7)
  A.recursive(6)
  A.recursive(5)
  A.recursive(4)
  A.recursive(3)
  A.recursive(2)
  A.recursive(1)
  A.recursive(0)
  </code></pre>
  
  <p>Let's get to the the confusing part. Now we call <code>recursive</code> in class B.</p>
  
  <p><strong>Expected</strong>:</p>
  
  <pre><code>B.recursive(10)
  A.recursive(11)
  A.recursive(10)
  A.recursive(9)
  A.recursive(8)
  A.recursive(7)
  A.recursive(6)
  A.recursive(5)
  A.recursive(4)
  A.recursive(3)
  A.recursive(2)
  A.recursive(1)
  A.recursive(0)
  </code></pre>
  
  <p><strong>Actual</strong>:</p>
  
  <pre><code>B.recursive(10)
  A.recursive(11)
  B.recursive(10)
  A.recursive(11)
  B.recursive(10)
  A.recursive(11)
  B.recursive(10)
  ..infinite loop...
  </code></pre>
  
  <p>How does this happen? I know this is a devised example, but it makes me wonder.</p>
  
  <p>Older question with a <a href="https://stackoverflow.com/questions/10357029/java-inheritance-and-recursion" title="Older question">concrete use case</a>.</p>