title: Trying to understand the difference between two polymorphic commands in Java
body: <p>I have these two classes:</p>
  
  <pre><code>public class A {
      private final static A five = new A(5);
      public final int x;
      public A(int x) {
          this.x = x;
      }
      public boolean equals(Object o) {
          return x == ((A) o).x;
      }
      public String toString() {
          return equals(five) ? "five" : (x + "");
      }
  }
  
  public class B extends A {
      public final int x;
      public B(int x) {
          super(x);
          this.x = x + 1;
      }
      public boolean equals(A o) {
          return x == o.x;
      }
      public String toString() {
          return "B: " + super.toString();
      }
  }
  </code></pre>
  
  <p>These are the 2 lines in my <code>main</code> program:</p>
  
  <pre><code>System.out.println(new B(5));
  System.out.println((new B(5)).equals(new A(5)));
  </code></pre>
  
  <p>I know that in Java the method called is decided by the Object type,
  in both of the lines the Object is of type <code>B</code>, so in the first line i have a call to <code>B</code> class <code>toString()</code> method,
  from there after it prints "B: " it calls <code>A</code> class <code>toString()</code>, and now it tries to activate the <code>equals()</code> method.
  From my understanding on polymorphism in Java the Object type i still <code>B</code>, so it will try to activate <code>B</code>'s <code>equals()</code> method, but actually while debugging it activates the <code>A</code> class <code>equals()</code>, that's the first thing i don't understand.</p>
  
  <p>Later in the 2nd line of my <code>main</code> program i'm initializing a <code>B</code> Object, and calling the <code>equals()</code> method, so after i've seen how the first line of code behaves i said well OK, i'll call the <code>A</code> <code>equals()</code> but in practice this line goes to <code>B</code>'s <code>equals</code>...</p>
  
  <p>I'm a bit confused, first the 2 lines of my <code>main</code> program behaves differently from what i know about how polymorphic code works, and the 2 lines behave differently although they should act the same...</p>
  
  <p>Hope you could enlighten me about how this code works and why.</p>