title: Java Type Wildcarding
body: <p>(For the purposes of this post, lets set aside java.util.Observable)</p>
  
  <p>I was experimenting around with generics, and then wildcard types. The aim was to create a type-generic observable cache with deltas provided to the observers. Where this starts to go off the rails is I wanted to allow more generic observers to be used than the one specified in the Observable, e.g. <code>Observer&lt;Object&gt;</code> or some other common superclass.</p>
  
  <p>I've since concluded that this is overly complex for my use case, but the problem itself continues to bother me since I clearly don't understand how to use type wildcarding properly.</p>
  
  <p>So if we start with a simple observer interface:</p>
  
  <pre><code>public interface Observer&lt;T&gt; {
      public void notifyChange(ChangeHolder&lt;T&gt; change);
  }
  </code></pre>
  
  <p>And the associated ChangeHolder, in a full implementation this would be more complex, providing lists of added / updated / deleted objects, but this is sufficient to demonstrate the issue</p>
  
  <pre><code>public interface ChangeHolder&lt;T&gt; {
      T getChange();
  }
  </code></pre>
  
  <p>So with the Observer defined, I tried to implement the Observable abstract class:</p>
  
  <pre><code>public abstract class Observable&lt;T&gt; {
      private Set&lt;Observer&lt;? super T&gt;&gt; observers = new HashSet&lt;&gt;();
  
      public void addObserver(Observer&lt;? super T&gt; obs){
          observers.add(obs);
      }
  
      public void change(ChangeHolder&lt;T&gt; changes){
          for(Observer&lt;? super T&gt; obs : observers){
              obs.notifyChange(changes);
          }
      }
  }
  </code></pre>
  
  <p>And with that I could define some object caches, by declaring something like <code>class TreeCache extends ObservableCache&lt;Tree&gt;</code>, (From this point on I'll use Tree as an example class to be used as a T, assume it to be a simple POJO extending only from Object) and pass <code>ChangeHolder&lt;Tree&gt;</code> objects to <code>TreeCache.change()</code>  when necessary. Unfortunately the compiler disagrees:</p>
  
  <pre><code>The method notifyChange(ChangeHolder&lt;capture#2-of ? super T&gt;) in the type Observer&lt;capture#2-of ? super T&gt; is not applicable for the arguments (ChangeHolder&lt;T&gt;)
  </code></pre>
  
  <p>Which is where my understanding ends. </p>
  
  <p>Without the ChangeHolder class (if my notifyChange method just took a plain T instead) it works just fine since it's perfectly legal to pass a Tree to Observer.notifyChange(Object).</p>
  
  <p>I inferred that I should be able to do the same with the ChangeHolder - <code>ChangeHolder&lt;T&gt;</code> should satisfy <code>notifyChange(ChangeHolder&lt;? super T&gt;)</code> in the same way that <code>T</code> satisfies <code>notifyChange(? super T)</code> but clearly I am  misunderstanding something?</p>