title: Java Generics - Choosing the correct generic service
body: <p>Lets say we have a product of different types, the different types have different internal variables and does not share anything beside the fact they are all products.</p>
  
  <pre><code>public interface Product {}
  public class ProductA implements Product {
      private String productAVariable;
      // getters
  }
  public class ProductB implements Product {
      private String productBVariable;
      // getters
  }
  </code></pre>
  
  <p>To get the quote/price of a product we must call an external service:</p>
  
  <pre><code>public interface QuoteService&lt;T extends Product&gt; {
      ProductPrice getQuote(T product);
  }
  public class ProductAQuoteService implements QuoteService&lt;ProductA&gt; {
      @Override
      public ProductPrice getQuote(ProductA product) {
          return new ProductPrice(someExternalService.getQuote(product.getProductAVariable()));
      }
  }
  public class ProductBQuoteService implements QuoteService&lt;ProductB&gt; {
      @Override
      public ProductPrice getQuote(ProductB product) {
          return new ProductPrice(someOtherExternalService.getQuote(product.getProductBVariable()));
      }
  }
  </code></pre>
  
  <p>So far so good. The last step is to iterate through a List of Products in our shoppingcart. Fetching the price/quote for each one. But how can we do that in a generic way? Currently i have some if-else instance of statements, but I feel there must be something more generic?</p>
  
  <pre><code>List&lt;Product&gt; productsInCart = Lists.asList(new ProductA(), new ProductB());
  for (Product product : productsInCart) {
      if (product instanceof ProductA) {
          productAQuoteService.getQuote((ProductA) product);
      } else if (product instanceof ProductB) {
          productBQuoteService.getQuote((ProductB) product);
      }
  }
  </code></pre>