I just started messing with generics and I want to make sure I got this right, any help?
public interface Cart<T extends CartItem> {
public void setItems(List<T> items);
public List<T> getItems();
}
public interface CartItem {
public BigDecimal getQty();
public void setQty(BigDecimal qty);
// more
}
public class CartService<T extends Cart<E>, E extends CartItem> {
public void addOrReplaceItem(T cart, E newCartItem) {
List<E> items = cart.getItems();
int position = items.indexOf(newCartItem);
if(position > -1) {
E existingItem = items.get(position);
existingItem.setQty(existingItem.getQty()
.add(newCartItem.getQty()));
} else {
items.add(newCartItem);
}
}
}
public interface GroceryCart extends Cart<GroceryCartItemImpl>{
// more
}
public interface GroceryCartItem extends CartItem {
// more
}
public class GroceryCartItemImpl implements Serializable, GroceryCartItem {
// more
}
public class GroceryCartImpl implements Serializable, GroceryCart {
// more
}
Calling CartService:
GroceryCartImpl gc = ............
GroceryCartItemImpl gci = ...........
CartService<GroceryCartImpl, GroceryCartItemImpl> cs =
new CartService<GroceryCartImpl, GroceryCartItemImpl>();
cs.addOrReplaceItem(gc, gci);