title: Java: Casting to Generic with Interface Pointers
body: <p>In the following sample code two classes <code>EventA</code> and <code>EventB</code> both implement the <code>interface Historical</code>.  Java can automatically cast an <code>EventA</code> or <code>EventB</code> to <code>Historical</code> when one of these objects is passed as a parameter, as in the <code>examineEvent</code> method below.  However, Java is no longer able to cast when a generic is introduced ie. from <code>List&lt;EventA&gt;</code> to <code>List&lt;Historical&gt;</code> -- Unless the target function (in this case <code>findClosestValidEventIndex</code>) is declared using <code>List&lt;? extends Historical&gt;</code>.  </p>
  
  <p>Can someone explain why this must be? It seems to me that the very use of an interface in a generic should automatically imply the <code>&lt;? extends Interface&gt;</code>.</p>
  
  <pre><code>public class SampleApplication {
  
     public interface Historical {
        public DateTime getDate();
     }   
  
     public static class EventA implements Historical {
        private DateTime date;
        @Override
        public DateTime getDate() {
           return date;
        }
     }
  
     public static class EventB implements Historical {
        private DateTime date;
        @Override
        public DateTime getDate() {
           return date;
        }
     } 
  
     private static int findClosestValidEventIndex(List&lt;Historical&gt; history, DateTime when) {
        // do some processing
        return i;
     }
  
     private static int examineEvent(Historical event){
        return j;
     }
  
     public static void main(String[] args) {
        DateTime target = new DateTime();
        // AOK
        EventA a = new EventA(target);
        int idy = examineEvent(a);
        // Type Error --- Unless 
        List&lt;EventA&gt; alist = new ArrayList&lt;EventA&gt;();
        int idx = findClosestValidEventIndex(alist, target);
     }
  }
  </code></pre>