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 items; 1
public Bundle()
{
items = new LinkedList(); 2
}
public void add(Product p)
{
items.add(p);
}
public double getPrice()
{
double price = 0.0;
Iterator itr = items.iterator();
while (itr.hasNext())
price += ((Product)itr.next()).getPrice();
return price;
}
} 3
Notes:
- Or declare a specific type of list:
private LinkedList items;
or
private ArrayList items;
- Or
new ArrayList() .
- In an alternative solution, this class would simply extend
ArrayList or
LinkedList .
Then neither the constructor nor the add method
would be needed:
public class Bundle extends LinkedList implements Product
{
public double getPrice()
{
double price = 0.0;
Iterator itr = iterator();
while (itr.hasNext())
price += ((Product)itr.next()).getPrice();
return price;
}
}
|