Java - Passing objects polymorphically to methods accepting Generic arguments
<p>I was reading "Head First Java" - pretty cool book to get started on Java. I have a question with regards to Generics. </p>

<p>The book had correctly stated that it is not possible to polymorphically pass a subtype to method accepting ArrayList. Example below -</p>

<pre><code>public class Animal {

}

public class Dog extends Animal {

}

public class Cat extends Animal {

}

public class AnimalTester {
    public static void main (String[] args) {
      new AnimalTester().go(); 
    }


    public void go() {
      List&lt;Animal&gt; animalList=new ArrayList&lt;Animal&gt;(); 
      List&lt;Dog&gt; dogList=new ArrayList&lt;Dog&gt;();
      processAnimals(animalList); // this would compile
      processAnimals(dogList); // this would not compile
    }

    public void processAnimals(List&lt;Animal&gt; animalList) {

    }

}
</code></pre>

<p>However the above can be fixed by the use of generics -</p>

<pre><code>public &lt;T extends Animal&gt; void processAnimals(List&lt;T&gt; animalList) {

}
</code></pre>

<p>But in the above case compiler would throw an exception if anything is tried to be added to the list (this is mentioned in the book). I tried it using my IDE and it did thrown an exception. The book had also mentioned that this is to ensure incorrect objects(e.g. cat) from being added to the list (dogList in our case). </p>

<p>However I am able to do this by casting the cat / dog / animal object using (T).</p>

<pre><code>public &lt;T extends Animal&gt; void processAnimals(List&lt;T&gt; animalList) {
   animalList.add(new Animal()); // compilation Error
   animalList.add(new Dog()); // compilation Error
   animalList.add(new Cat()); // compilation Error
   animalList.add((T) new Cat()); // works and I can also cast it back 
                                  // to Cat and get a Cat object
}
</code></pre>

<p>As per the book, the whole reason why Java creators threw an exception is because incorrect object should not be added to the list. However is Java allowing it because the programmer is explicitly casting it and thereby saying "I know what I am doing"?</p>
