title: Casting & Inheritance in Java
body: <p>I encountered a piece of code similar to the one below and was sure that its output would be <code>B</code>, since the variable <code>y</code> is cast to <code>class B</code> before calling <code>x()</code>, but instead, the program prints <code>C</code>. So I have two questions:</p>
  <ol>
  <li>Why is <code>C.x()</code> called instead of <code>B.x()</code>? Why does Java remember a variable's original type after it's been cast to a new type?</li>
  <li>How would I call <code>B.x()</code>?</li>
  </ol>
  <pre class="lang-java prettyprint-override"><code>class A {
      public void x() {
          System.out.println(&quot;A&quot;);
      }
  }
  
  class B extends A {
      @Override
      public void x() {
          System.out.println(&quot;B&quot;);
      }
  }
  
  class C extends B {
      @Override
      public void x() {
          System.out.println(&quot;C&quot;);
      }
  }
  
  public class Main {
      public static void main(String args[]) {
          A y = new C();
          ((B)y).x();
      }
  }
  </code></pre>