Define a class named MultiItemSale that represents a sale of multiple items of type Sale given in Display 8.1 (or of the types of any of its descendent classes). The class MultiItemSale will have an instance variable whose type is Sale[] , which will be used as a partially filled array. There will also be another instance variable of type int that keeps track of how much of this array is currently used. The exact details on methods and other instance variables, if any, are up to you. Use this class in a program that obtains information for items of type Sale and of type DiscountSale ( Display 8.2 ) and that computes the total bill for the list of items sold.
Program:
NOTE: Refer the textbook for the Sale.java and DiscountSale.java files.
// MultiItemSale.java
public class MultiItemSale
{
private Sale[] sales;
private int count;
public MultiItemSale()
{
sales = new Sale[100];
count = 0;
}
public MultiItemSale(int maxSize)
{
sales = new Sale[maxSize];
count = 0;
}
public void addSale(Sale sale)
{
if(count < sales.length)
{
sales[count] = sale;
count++;
}
}
public Sale getSale(int index)
{
if(index < 0 || index >= count)
return null;
return sales[index];
}
public double getTotalBill()
{
double total = 0;
for(int i = 0; i < count; i++)
{
total = total + sales[i].bill();
}
return total;
}
public String toString()
{
String result = "";
for(int i = 0; i < count; i++)
{
result = result + sales[i] + "\n";
}
result = result + "\n" + "Total bill = $"
+ String.format("%.2f", getTotalBill());
return result;
}
}
// Sale.java
public class Sale
{
// Refer the textbook for the code of this Sale class
}
// DiscountSale.java
public class DiscountSale extends Sale
{
// Refer the textbook for the code of this DiscountSale class
}
// MultiItemSaleTest.java
public class MultiItemSaleTest
{
public static void main(String[] args)
{
Sale sale1 = new Sale("Atomic coffee mug", 111.00);
Sale sale2 = new Sale("Cup holder", 11.90);
Sale sale3 = new Sale("Tire gauge", 8.80);
DiscountSale discSale1 =
new DiscountSale("Invisible paint", 6.50, 12);
DiscountSale discSale2 =
new DiscountSale("Floor mat", 10.90, 10);
DiscountSale discSale3 = new DiscountSale("Paint", 13, 9);
DiscountSale discSale4 = new DiscountSale("Map", 7.95, 0);
MultiItemSale multiSales = new MultiItemSale();
multiSales.addSale(sale1);
multiSales.addSale(sale2);
multiSales.addSale(sale3);
multiSales.addSale(discSale1);
multiSales.addSale(discSale2);
multiSales.addSale(discSale3);
multiSales.addSale(discSale4);
System.out.println(multiSales);
}
}
Output:
Atomic coffee mug Price and total cost = $111.0
Cup holder Price and total cost = $11.9
Tire gauge Price and total cost = $8.8
Invisible paint Price = $6.5 Discount = 12.0%
Total cost = $5.72
Floor mat Price = $10.9 Discount = 10.0%
Total cost = $9.81
Paint Price = $13.0 Discount = 9.0%
Total cost = $11.83
Map Price = $7.95 Discount = 0.0%
Total cost = $7.95
Total bill = $167.01