85.1k views
3 votes
For this homework assignment, you will be writing software in support of a Dessert Shoppe which sells candy by the pound, cookies by the dozen, ice cream, and sundaes (ice cream with a topping). To do this, you will implement an inheritance hierarchy of classes derived from a DessertItem superclass.

a. The Candy, Cookie, and IceCream classes will be derived from the DessertItem class.
b. The Sundae class will be derived from the IceCream class.

1 Answer

2 votes

Answer:

DessertItem.java

public abstract class DessertItem

{

protected String name;

// methods

abstract double calculateAndGetCost();

abstract String getReceiptItem();

}

Candy.java

public class Candy extends DessertItem

{

private double weight, pricePerPound, cost;

public Candy(String name, double weight, double pricePerPound) {

this.name = name;

this.weight = weight;

this.pricePerPound = pricePerPound;

}

public double calculateAndGetCost()

{

this.cost = Math.round((weight * pricePerPound)*100) / 100.0;

return this.cost;

}

public String getReceiptItem()

{

String item = weight + " lbs. @ " + pricePerPound + " /lb.\\";

item += String.format("%-10s\t%.2f\\", name, cost);

return item;

}

}

Cookie.java

public class Cookie extends DessertItem

{

private int number;

private double pricePerDz, cost;

public Cookie(String name, int number, double pricePerDz) {

this.name = name;

this.number = number;

this.pricePerDz = pricePerDz;

}

public double calculateAndGetCost()

{

this.cost = Math.round((number * pricePerDz/12)*100) / 100.0;

return this.cost;

}

public String getReceiptItem()

{

String item = number + " @ " + pricePerDz + " /dz.\\";

item = String.format("%-10s\t%.2f\\", name, cost);

return item;

}

}

IceCream.java

public class IceCream extends DessertItem

{

private double cost;

public IceCream(String name, double cost) {

this.name = name;

this.cost = cost;

}

public double calculateAndGetCost()

{

return this.cost;

}

public String getReceiptItem()

{

String item = String.format("%-10s\t%.2f\\", name, cost);

return item;

}

}

Sundae.java

public class Sundae extends IceCream

{

private double toppingsCost, cost;

public Sundae(String name, double iceCost, double toppingsCost) {

super(name, iceCost);

this.toppingsCost = toppingsCost;

}

public double calculateAndGetCost()

{

this.cost = super.calculateAndGetCost() + this.toppingsCost;

return this.cost;

}

public String getReceiptItem()

{

int index = name.indexOf("with");

String item = name.substring(0, index) + "with\\";

item += String.format("%-10s\t%.2f\\", name.substring(index+5), cost);

return item;

}

}

User Stackdisplay
by
4.4k points