Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple objects to array

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.

like image 561
TH3Mitch Avatar asked May 16 '26 21:05

TH3Mitch


2 Answers

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.

like image 167
Dan D. Avatar answered May 19 '26 10:05

Dan D.


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>();
like image 28
AlexWien Avatar answered May 19 '26 09:05

AlexWien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!