I'm currently making an easy webshop application. The webshop is required to add three kinds of objects to the shoping cart. A CD, a Book or a Game. I made a class for every object which all have a toString() method.
Now I have to make a method add(..) which needs to add the specified object to an ArrayList called shoppingcart. This method needs to be called within the class Webshop which in itself has the objects that are created.
I know how to do this with multiple add methods but it's required to do it with a single method.
You will probably want to create a new type called something like AbstractItem and all your other types extend from this. It is also a good practice to hide this abstract class behind an interface. So, the AbstraxtItem class could implement an Item interface that would define the public APIs.
The AbstractItem class would define some abstract methods that its subtypes should implement like getPrice() and possibly other concrete methods that would be the common behavior for all subclasses. The shopping cart will be an ArrayList<Item> and that would be populated by the add(Item) method.
Each object in your shop which can be add should implement an interface IProduct.
You then have a list of IProduct, which you can add.
ArrayList<IProduct> shoppingBasket = new ArrayList<IProduct>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With