title: Polymorphism in java: Why do we set parent reference to child object?
body: <p>I want to understand the use-case of setting a parent reference to a child object.
  Example: Dog class extends Animal class. (No interfaces, mind it)
  I would normally create an object of Dog like this:</p>
  <pre><code>Dog obj = new Dog();
  </code></pre>
  <p>Now, since Dog is a subclass of Animal it already has access to all of Animal's methods and variables. Then, what difference does this make:</p>
  <pre><code>Animal obj = new Dog(); 
  </code></pre>
  <p>Please provide a proper use-case with an code snippet of its use. No theoretical articles about 'Polymorphism' or 'Coding to interfaces' please!</p>
  <p>Code:</p>
  <pre><code>public class Polymorphism {
      public static void main(String[] args){
          Animal obj1 = new Dog();
          Dog obj2 = new Dog();
          obj1.shout(); //output is bark..
          obj2.shout(); //output is bark..        
      }   
  }
  
  class Animal{
      public void shout(){
          System.out.println(&quot;Parent animal's shout&quot;);
      }       
  }
  
  class Dog extends Animal{
      public void shout(){
          System.out.println(&quot;bark..&quot;);
      }
  }
  
  class Lion extends Animal{
      public void shout(){
          System.out.println(&quot;roar..&quot;);
      }
  }
  
  class Horse extends Animal{
      public void shout(){
          System.out.println(&quot;neigh&quot;);
      }
  }
  </code></pre>
  <p>Output is the same for both the cases. Then why do we set parent reference to child object?</p>