title: Java Generics enforcing compatible wildcards
body: <p>I've these classes.</p>
  
  <pre><code>class RedSocket {}
  class GreenSocket {}
  class RedWire {}
  class GreenWire {}
  </code></pre>
  
  <p>I've a class which uses 2 generic types </p>
  
  <pre><code>public class Connection&lt;W, S&gt; {}
  </code></pre>
  
  <p>where W is Wire type &amp; S is Socket type. </p>
  
  <p>I'm trying to enforce compile time check to ensure that socket &amp; wire have the same color. </p>
  
  <p>I tried doing this:</p>
  
  <pre><code>public class Connection&lt;W extends Wire &amp; Color, S extends Socket &amp; Color&gt; {}
  
  interface Color {}
  
  interface Red extends Color {}
  interface Green extends Color {}
  
  interface Socket {}
  interface Wire {}
  
  class RedSocket implements Socket, Red {}
  class GreenSocket implements Socket, Green {}
  class RedWire implements Wire,  Red {}
  class GreenWire implements Wire, Green {}
  </code></pre>
  
  <p>But this doesn't really ensure that the <code>Color</code> used is same for both generic types and still lets me do this:</p>
  
  <pre><code>public class Connection&lt;W extends Wire &amp; Color, S extends Socket &amp; Color&gt; {
      public static void main(String[] args) {
          new Connection&lt;RedWire, GreenSocket&gt;();
          new Connection&lt;GreenWire, RedSocket&gt;();
      }
  }
  </code></pre>
  
  <p>(Why this happens has been explained brilliantly by Radiodef <a href="https://stackoverflow.com/questions/30217236/can-the-generic-type-of-a-generic-java-method-be-used-to-enforce-the-type-of-arg">here</a>)</p>
  
  <p>How can I enforce compile time check to ensure that socket &amp; wire have the same color?</p>