While making a call to a method, with a refrence of parent class which is refering to an object of child class, why is it mandatory to have that method in Parent class too?
<pre><code>public class A
{  }

public class B extends A
{
  public void add()
  {
   System.out.println("add in B");
  }
}
</code></pre>

<p>Now here if we call add in following way hen it gives an error:
A a1 = new B;
a1.add();</p>

<p>But when we add the add() method in class A and then call in the similar fashion then add() method of child class is called.  </p>

<p>i.e.</p>

<pre><code>public class A
{
  public void add()
  {
   System.out.println("add in A");
  }
}

public class B extends A
{
  public void add()
  {
   System.out.println("add in B");
  }
}
</code></pre>

<p>call:</p>

<pre><code>A a1 = new B;
a1.add();
</code></pre>

<p>output:</p>

<blockquote>
  <p>add in B</p>
</blockquote>

<p>Why is it so?</p>
