title: Java Factory Pattern With Generics
body: <p>I would like my <code>BallUserInterfaceFactory</code> to return an instance of a user interface that has the proper generic type. I am stuck in the example below getting the error: </p>
  
  <blockquote>
    <p>Bound mismatch: The generic method getBaseballUserInterface(BASEBALL)
    of type BallUserInterfaceFactory is not applicable for the arguments
    (BALL). The inferred type BALL is not a valid substitute for the
    bounded parameter </p>
  </blockquote>
  
  <pre><code>public class BallUserInterfaceFactory {
      public static &lt;BALL extends Ball&gt; BallUserInterface&lt;BALL&gt; getUserInterface(BALL ball) {
  
          if(ball instanceof Baseball){
              return getBaseballUserInterface(ball);
          }
          //Other ball types go here
  
          //Unable to create a UI for ball
          return null;
      }
  
      private static &lt;BASEBALL extends Baseball&gt; BaseballUserInterface&lt;BASEBALL&gt; getBaseballUserInterface(BASEBALL ball){
          return new BaseballUserInterface&lt;BASEBALL&gt;(ball);
      }
  }
  </code></pre>
  
  <p>I understand that it cannot guarantee that BALL is a Baseball, and so there is a parameter type mismatch on the getBaseballUserInterface method call.</p>
  
  <p>If I cast the ball parameter in the getBaseballUserInterface method call, then I get the error:</p>
  
  <blockquote>
    <p>Type mismatch: cannot convert from <code>BaseballUserInterface&lt;Baseball&gt;</code>
    to <code>BallUserInterface&lt;BALL&gt;</code></p>
  </blockquote>
  
  <p>Because it can't guarantee that what I am returning is the same type of BALL.</p>
  
  <p><strong>My question is, what is the strategy for dealing with this situation?</strong></p>
  
  <p>(For completeness, here are the other classes required in the example)</p>
  
  <pre><code>public class Ball {
  
  }
  
  public class Baseball extends Ball {
  
  }
  
  public class BallUserInterface &lt;BALL extends Ball&gt; {
  
      private BALL ball;
  
      public BallUserInterface(BALL ball){
          this.ball = ball;
      }
  }
  
  public class BaseballUserInterface&lt;BASEBALL extends Baseball&gt; extends BallUserInterface&lt;BASEBALL&gt;{
  
      public BaseballUserInterface(BASEBALL ball) {
          super(ball);
      }
  
  }
  </code></pre>