title: Why doesn't Java automatically access the overridden method?
body: <p>Given two classes, a parent class and a child class:</p>
  <pre><code>class A {
      private void greet() {
          System.out.println(&quot;Class A&quot;);
      }
  }
  
  class B extends A {
      public void greet() {
          System.out.println(&quot;Class B&quot;);
      }
  }
  </code></pre>
  <p>One has a method called <code>greet()</code>, which is <code>private</code>, and the other one defines a method with the same name, only that it is <code>public</code>. Now, as far as I know, the child's <code>greet()</code> method doesn't override the parent's method, because it 'hides' it? (given the fact that private methods can't be overridden?)</p>
  <p>Now, given the following class and method (considered to be in the same package as <code>A</code> and <code>B</code>):</p>
  <pre><code>public class Main {
      public static void main(String[] args) {
          B b = new B();
          b.greet();
      }
  }
  </code></pre>
  <p>This should compile. But this one:</p>
  <pre><code>public class Main {
      public static void main(String[] args) {
          A a = new B();
          b.greet();
      }
  }
  </code></pre>
  <p>This one up here doesn't compile, because it's missing a typecast.
  My question would be: why? If the <code>greet()</code> method was <code>public</code> in both places, it would have shown <code>Class B</code> both times. I'm pretty confused about why Java doesn't figure at runtime, for the second case, that <code>a</code> is actually referencing to an object of type <code>B</code>, and directly calls the method from class <code>B</code>.</p>
  <p>Tried reading more about polymorphism in an OCA-preparation book, but the authors didn't seem to be so specific about it.</p>