Part (a)
public class Pack implements Product
{
private int quantity;
private Product product;
public Pack(int qty, Product p)
{
quantity = qty;
product = p;
}
public double getPrice()
{
return quantity * product.getPrice();
}
}
Part (b)
public class Bundle implements Product
{
private List<Product> items; 1
public Bundle()
{
items = new LinkedList<Product>(); 1
}
public void add(Product p)
{
items.add(p);
}
public double getPrice()
{
double price = 0.0;
for (Product item : items)
price += item.getPrice();
return price;
}
} 3
Notes:
- Or declare a specific type of list:
private LinkedList<Product> items;
or
private ArrayList<Product> items;
- Or
new ArrayList<Product>() .
- In an alternative solution, this class would simply extend
ArrayList<Product> or
LinkedList<Product> .
Then neither the constructor nor the add method
would be needed:
public class Bundle extends LinkedList<Product> implements Product
{
public double getPrice()
{
double price = 0.0;
for (Product item : items)
price += item.getPrice();
return price;
}
}
|