title: Java dynamic binding and method overriding
body: <p>Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...</p>
  
  <p>Here's the problem I was given:</p>
  
  <pre><code>/* What is the output of the following program? */
  
  public class Test {
  
    public boolean equals( Test other ) {
      System.out.println( "Inside of Test.equals" );
      return false;
    }
  
    public static void main( String [] args ) {
      Object t1 = new Test();
      Object t2 = new Test();
      Test t3 = new Test();
      Object o1 = new Object();
  
      int count = 0;
      System.out.println( count++ );// prints 0
      t1.equals( t2 ) ;
      System.out.println( count++ );// prints 1
      t1.equals( t3 );
      System.out.println( count++ );// prints 2
      t3.equals( o1 );
      System.out.println( count++ );// prints 3
      t3.equals(t3);
      System.out.println( count++ );// prints 4
      t3.equals(t2);
    }
  }
  </code></pre>
  
  <p>I asserted that the output should have been two separate print statements from within the overridden <code>equals()</code> method: at <code>t1.equals(t3)</code> and <code>t3.equals(t3)</code>.  The latter case is obvious enough, and with the former case, even though <code>t1</code> has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.</p>
  
  <p>Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line <code>t3.equals(t3)</code>.</p>
  
  <p>My question then is, why?  As I mentioned already, even though <code>t1</code> is a reference of type Object (so static binding would invoke Object's <code>equals()</code> method), dynamic binding <em>should</em> take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?</p>