title: Java Parametric Polymorphism example
body: <p>I have a question about Parametric Polymorphism. How do I determine the actual type and avoid casting If I have a collection with a mix of child types. For example </p>
  
  <pre><code>    class Animal{
  
      }
  
      class Bird extends Animal{
            void fly(){}
      }
  
      class Dog extends Animal{
            void bark(){}
      }
  
      ArrayList&lt;Animal&gt; list = new ArrayList&lt;Animal&gt;();
  </code></pre>
  
  <p>The problem is how do I know which one is which when I iterating through the Animal collection. Do I need to use instanceof to check the actual type every time?</p>
  
  <pre><code>    for(Animal animal : list){
            if(animal instanceof Dog){
                  ((Dog) animal).bark();
            } 
            else ((Bird) animal).fly();             
      }
  </code></pre>