Out put a bit off for method - java

So this class is inheriting things from other classes which when the client class is used will run all of this.
So far my output is
Your drink choice was: The name of the drink :Black coffeeand its price is: 3.0and the size is :2
When I write in the parameters "Coffee coffee = new Coffee("Black coffee",1,2,"Mocha");" into the client class.
This isn't quite right and I also need to calculate the total but I can't figure out where I need to put that bit of code.
public class Drinks extends CoffeeShop {
private String name; // default name
private double price_per_oz= .10; // default price per oz
private int size = 6;// default value
public Drinks(){
super();
}
public Drinks(String name,double price_per_oz,int size){
this.name = name;
this.price_per_oz = price_per_oz;
this.size = size;
}
public String toString(){
return ("The name of the drink :"+ name +
"and its price is: "+price_per_oz+
"and the size is :"+ size );
}
public double getPrice(){
return price_per_oz*size;
}
//getter setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice_per_oz() {
return price_per_oz;
}
public void setPrice_per_oz(double price_per_oz) {
this.price_per_oz = price_per_oz;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
inherited class:
public class CoffeeShop {
public CoffeeShop(){
}
public static void main (String [] args){
Coffee coffee = new Coffee("Black coffee",1,2,"Mocha");
Tea tea = new Tea ("Hot", 10,12, "Earl Grey");
}
}
coffee class:
public class Coffee extends CaffeinatedDrinks {
private String type="drip"; // default type
public Coffee(){
super();
}
public Coffee(String name,double price_per_oz,int size,String type){
super(name,price_per_oz,size);// inherit these from parent
this.type = type; // make type available to use
System.out.println(" "+"Your drink choice was:"+ " " + this);
}
public double getPrice(){
if(6 == super.getSize()){ // if default size then use default price
return super.getPrice();
}
else if(12 == super.getSize()){ // otherwise charge them more
return super.getPrice()+0.5;
}
else{
//must be the large
return super.getPrice()+1;
}
}
}
Tea class:
public class Tea extends CaffeinatedDrinks {
private String flavor =" English Breakfast"; // default flavor
public Tea(){
super();//inherit parent class
}
public Tea (String name,double price_per_oz,int size,String flavor){
super(name,price_per_oz,size);
this.flavor = flavor;
//define flavor in constructor method
}
public double getPrice(){
if(6 == super.getSize()){
return super.getPrice();
}
else if(12 == super.getSize()){
return super.getPrice();
}
else{
//must be the large
return super.getPrice();
}
}
}
Caffeinated drinks class:
public class CaffeinatedDrinks extends Drinks {
public CaffeinatedDrinks(){
super();// inherit parent class Drinks
}
public CaffeinatedDrinks(String name,double price_per_oz,int size){
super(name,price_per_oz*3,size);// take the price per oz from parent function and multiply it by 3
}
}
public class NonCaffeinatedDrinks extends Drinks {
public NonCaffeinatedDrinks(){
super();// inherit parent class drinks
}
public NonCaffeinatedDrinks(String name,double price_per_oz,int size){
super(name,price_per_oz*2,size);// take the price per oz from parent function and multiply it by 2
}
}
expected out put is something like this:
Your drink order consists of:
water, size small, cost :$0.60
coffee, type mocha, size medium, cost: $2.30
tea, flavor earl grey size large, cost: $1.20
The total cost of your order is: $4.10

Related

How to use polymorphism to access a method inside a subclass that is not defined in the super class using a reference variable of a superclass

If i have 2 classes the first one is BasicHamburger
public class BasicHamburger {
private String breadRollType;
private String meat;
private boolean lettuce;
private boolean tomato;
private boolean carrot;
private boolean cheese;
private int numberOfAdditions;
private int price;
public BasicHamburger(String breadRollType , String meat ,int price){
this.breadRollType = breadRollType;
this.meat = meat;
this.price = price;
lettuce = false;
tomato = false;
carrot = false;
cheese = false;
numberOfAdditions = 0;
}
public void addLettuce(){
lettuce = true;
incrementNumberOfAdditions();
}
public void addTomato(){
tomato = true;
incrementNumberOfAdditions();
}
public void addCarrot(){
carrot = true;
incrementNumberOfAdditions();
}
public void addCheese(){
cheese = true;
incrementNumberOfAdditions();
}
public int getNumberOfAdditions(){
return numberOfAdditions;
}
protected int incrementNumberOfAdditions(){
return ++numberOfAdditions;
}
public boolean isLettuce() {
return lettuce;
}
public boolean isTomato() {
return tomato;
}
public boolean isCarrot() {
return carrot;
}
public boolean isCheese() {
return cheese;
}
public int getBasicHamburgerPrice(){
return price;
}
public int getLettucePrice(){
return 20;
}
public int getTomatoPrice(){
return 15;
}
public int getCheesePrice(){
return 40;
}
public int getCarrotPrice(){
return 10;
}
public int getTotalBasicHamburgerPrice(){
if(isCarrot()){
price = price + 10;
}
if(isCheese()){
price = price + 40;
}
if(isTomato()){
price = price + 15;
}
if(isLettuce()){
price = price + 20;
}
return price;
}
public void displayBurgerDetailsWithPrices(){
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
System.out.println("Basic Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Basic Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
the second class is HealthyBurger
public class HealthyBurger extends BasicHamburger{
private boolean onion;
private boolean bacon;
public HealthyBurger(){
super("Brown Rye ","Mutton",30);
onion = false;
bacon = false;
}
public boolean isOnion() {
return onion;
}
public boolean isBacon() {
return bacon;
}
public void addOnion(){
onion = true;
incrementNumberOfAdditions();
}
public void addBacon(){
bacon = true;
incrementNumberOfAdditions();
}
public int getOnionPrice(){
return 15;
}
public int getBaconPrice(){
return 20;
}
#Override
public int getTotalBasicHamburgerPrice() {
int newPrice = super.getTotalBasicHamburgerPrice();
if(isBacon()){
newPrice += 20;
}
if(isOnion()){
newPrice +=15;
}
return newPrice;
}
#Override
public void displayBurgerDetailsWithPrices() {
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
if(isOnion()){
System.out.println("Onion addition = "+getOnionPrice());
}
if(isBacon()){
System.out.println("Bacon addition = "+getBaconPrice());
}
System.out.println("Healthy Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Healthy Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
in the main i have written this code
public class Main {
public static void DisplayBurger(BasicHamburger burger){
burger.displayBurgerDetailsWithPrices();
}
public static void main(String[] args) {
BasicHamburger ham1 = new BasicHamburger("x","beef",20);
ham1.addCarrot();
ham1.addCheese();
ham1.addLettuce();
ham1.addTomato();
HealthyBurger ham2 = new HealthyBurger();
ham2.addOnion();
ham2.addBacon();
BasicHamburger test = ham2;
DisplayBurger(test);
}
}
My confusion is the test variable can access displayBurgerDetailsWithPrices() function inside HealthyBurger class and can call the isOnion which is inside that function. Whereas if i decided to write that code inside the main i can not access the isOnion() function.
BasicHamburger newBurger = new HealthyBurger();
newBurger.isOnion();
To make the question clear and right to the point , why accessing a function inside a subclass through a overriden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
BasicHamburger newBurger = new HealthyBurger();
boolean onion = false;
if(newBurger instanceof HealthyBurger)
onion = ((HealthyBurger).isOnion());
To make the question clear and right to the point, why accessing a function inside a subclass through an overridden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
It calles Polymophism. The object reference BasicHamburger newBurger refers to the instance of class BasicHamburger or any of its children. It means that by default you have access only to the methods declared in BasicHamburger or any of its parent. If you want to call the children's method, you have to cast this reference to the required type.
I would redesign your code, because in general case if you use casting, then it looks like a design problem (repeat: in general; sometimes it really needed).
public abstract class Burger {
protected final String breadRollType;
protected final String meat;
protected final int basePrice;
protected final Set<Ingredient> ingredients;
protected Burger(String breadRollType, String meat, int basePrice, Set<Ingredient> ingredients) {
this.breadRollType = breadRollType;
this.meat = meat;
this.basePrice = basePrice;
this.ingredients = ingredients == null || ingredients.isEmpty() ? Set.of() : Set.copyOf(ingredients);
}
public final int getBasePrice() {
return basePrice;
}
protected int getIngredientsPrice() {
return ingredients.stream()
.map(Ingredient::getPrice)
.mapToInt(i -> i)
.sum();
}
public int getTotalPrice() {
return basePrice + getIngredientsPrice();
}
public final int getTotalIngredients() {
return ingredients.size();
}
public final boolean hasIngredient(Ingredient ingredient) {
return ingredient != null && ingredients.contains(ingredient);
}
public void printDetailsWithPrices() {
System.out.println(breadRollType + ' ' + meat);
System.out.println("----");
System.out.println("Basic price: " + basePrice);
System.out.println("Ingredients price: " + getIngredientsPrice());
ingredients.forEach(ingredient -> System.out.format("-> %s price: %d\n",
ingredient.getTitle(), ingredient.getPrice()));
System.out.println("Total price: " + getTotalPrice());
}
protected interface Ingredient {
String getTitle();
int getPrice();
}
}
public class HealthyBurger extends Burger {
public HealthyBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
ONION("Onion", 15),
BACON("Bacon", 20);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public class PopularBurger extends Burger {
protected PopularBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
LETTUCE("Lettuce", 20),
TOMATO("Tomato", 25),
CARROT("Carrot", 10),
CHEESE("Cheese", 40);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public static void main(String... args) {
PopularBurger popularBurger = new PopularBurger("x", "beef", 20,
Set.of(PopularBurger.Ingredient.CARROT,
PopularBurger.Ingredient.CHEESE,
PopularBurger.Ingredient.LETTUCE,
PopularBurger.Ingredient.TOMATO));
HealthyBurger healthyBurger = new HealthyBurger("Brown Rye", "Mutton", 30,
Set.of(HealthyBurger.Ingredient.ONION,
HealthyBurger.Ingredient.BACON));
PopularBurger one = popularBurger;
one.printDetailsWithPrices();
System.out.println();
HealthyBurger two = healthyBurger;
two.printDetailsWithPrices();
System.out.println();
boolean withOnion = two.hasIngredient(HealthyBurger.Ingredient.ONION);
System.out.println(withOnion);
}
x beef
----
Basic price: 20
Ingredients price: 95
-> Cheese price: 40
-> Carrot price: 10
-> Lettuce price: 20
-> Tomato price: 25
Total price: 115
Brown Rye Mutton
----
Basic price: 30
Ingredients price: 35
-> Onion price: 15
-> Bacon price: 20
Total price: 65
true

Strategy design pattern Example?

Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}

Java Decorative Pattern Pizza Topping

i have to implement Pizza(American and Neapolitan) decoration pattern with 4 different toppings(Salami,Soudjouk,Onion,Pepper) which extends "TopingDecorator" class and out of them 3 will be added to pizza by "Add Pizza" command.However, the code does not add it to Pizza's TopingDecorator ArrayList. It should be something like below(I am trying to add Salami and Soudjouk to AmericanPan pizza(which extends PlainPizza class)):
AmericanPan a = new American();
Salami s = new Salami(a);
Soudjouk so = new Soudjouk(s);
Here is my PlainPizza class:
public class PlainPizza implements Pizza{
private int cost;
private String name;
private int orderID;
List<ToppingDecorator> topingsOfPizza;
public PlainPizza(int orderID){
this.orderID = orderID;
topingsOfPizza = new ArrayList<ToppingDecorator>();
}
public void addPizza(PlainPizza p) {
Pizza.allPizzas.add(p);
}
public List<ToppingDecorator> getTopingsOfPizza() {
return topingsOfPizza;
}
#Override
public int cost() {
// TODO Auto-generated method stub
return cost;
}
public int getOrderID() {
return orderID;
}
public String getName() {
return name;
}
#Override
public void addTopping() {
}
And here is my AmericanPan class:
public class AmericanPan extends PlainPizza{
// Class Instances
private final int cost = 5;
private String name;
// Constructor
public AmericanPan(int orderID) {
super(orderID);
this.name = "AmericanPan";
}
// Get Cost
#Override
public int cost() {
return cost;
}
// Get Name
public String getName() {
return name;
}
I am tryin to add Salami on American Pan in Salami class:
public class Salami extends ToppingDecorator{
private String name;
ToppingDecorator t;
public Salami(PlainPizza pizza) {
super(pizza);
this.name = "salami";
this.addToping();
}
#Override
public int cost() {
return super.cost() + 3;
}
#Override
public void addTopping() {
t = new Salami(pizza);
pizza.topingsOfPizza.add(t);
}
And I am trying to add it with code below in my function in main class which operates the whole process:
PlainPizza piz = new AmericanPan(orderID);
// Check The Toppings that Pizza contains
if(pizzatops.contains("soudjouk")){
soudjok = true;
}if(pizzatops.contains("salami")){
salami = true;
}if(pizzatops.contains("pepper")){
pepper = true;
}if(pizzatops.contains("onion")){
onion = true;
}
// Add Pizza according to Toppings
for(int g = 0;g<pizzatops.size();g++){
if(pizzatops.get(g).equals("salami")){
Salami s = new Salami(piz);
}else if(pizzatops.get(g).equals("pepper")){
Pepper p = new Pepper(piz);
}else if(pizzatops.get(g).equals("soudjouk")){
Soudjouk p = new Soudjouk(piz);
}
else if(pizzatops.get(g).equals("onion")){
Onion o = new Onion(piz);
}
}
Pizza.allPizzas.add(piz);
System.out.println("AmericanPan pizza added to order " + orderID);
You're going about this all wrong, with the decorator pattern you use different decorator classes to create different type of instances. In your case this means that you can't add multiple toppings to a pizza because the toppings are actually pizzas themselves, so Salami is a salami pizza and Pepper is a pepper pizza and not two toppings
If you want to add multiple toppings to one pizza then Decorator is not the right pattern.
Here is my simplified decorator implementation
interface Pizza {
int cost();
}
public class PlainPizza implements Pizza {
#Override
public int cost() {
return 10;
}
}
public abstract class ToppingDecorator implements Pizza {
private Pizza pizza;
public ToppingDecorator(PlainPizza aPizza) {
pizza = aPizza;
}
#Override
public int cost() {
return pizza.cost();
}
}
public class SalamiPizza extends ToppingDecorator {
public SalamiPizza(PlainPizza aPizza) {
super(aPizza);
}
#Override
public int cost() {
return super.cost() +3;
}
}
public static void main(String[] args) {
SalamiPizza p = new SalamiPizza(new PlainPizza());
System.out.print(p.cost());
}
I tnink, your implementation is wrong. Decorator pattern using interfaces, abstract classes.
Here
You can see, what is the right implementation with Java.

Given expected output and partially completed java program related to inheritance. Need help in completion. Constraint-Not to touch main method

This question was asked in my recent coding round. Its kind of tricky as we cannot modify getClass() and getClass().getName()
along with main method, Given are Food and FoodFactory class templates.
I had to print the following lines:
My name is Fastfood.
My name is Fruits.
Our superclass is Food
I'm serving Fastfood
I'm serving Fruit
Code:
/* Name of the class has to be "Main" only if the class is public. */
class FoodFactory{
public Food getFood(String string) {
// TODO Auto-generated method stub
return new Food(string);
}
public String toString(){
return "Food";
}
public static String getName(){
return "Food";
}
}
class Food{
String name;
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving "+name);
}
public String getName(){
return name;
}
}
class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
foodFactory myFoods = new foodFactory();
Food food1 = myFoods.getFood("Fastfood");
Food food2 = myFoods.getFood("Fruits");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: " + food1.getClass().getSuperclass().getName());
food1.servesFood();
food2.servesFood();
}
}
The key thing for this exercise is revealed by one word in your example output: superclass.
You want that getClass().getName() gives you different output. In order to get there, surprise: the objects you call getClass().getName() on ... need to have different classes!
Something like
class Food {
public void servesFood(){
System.out.println("I'm serving Food");
}
}
class FastFood extends Food {
#Override
public void servesFood(){
System.out.println("I'm serving Fastfood");
}
... similar for Fruit
If you now create instances of those two objects, they will give you the expected output. Now the question is: how are instances created?!
That is where your factory comes in:
class FoodFactory {
public Food getFood(String name) {
switch(name) {
case "FastFood" : return new Fastfood();
case "Fruit" : return new Fruit();
default: return new Food();
}
}
Please note: the above implementation assumes that any food that is not "Fastfood" or "Fruit"... is real "Food". And of course: you might expect that the actual "name" of the fruit ends up as some field within your Food class, but such refinements/extensions are left as exercise to the reader.
Here are the implementations of the two classes.
class FoodFactory{
private String name;
public Food getFood(String name){
this.name = name;
Food food = new Food(name);
return food;
}
public String getName{
return name;
}
}
class Food extends FoodFactory{
private String name;
public Food(String name){
this.name = name;
}
public void servesFood(){
System.out.println("I'm serving "+ name);
}
public String getName(){
return name;
}
}
This should work.
This one will work.
class FoodFactory extends Food {
public Food getFood(String string) {
if (string.equals("Fruit")) {
return new Fruit("Fruit");
} else {
return new FastFood("FastFood");
}
}
}
class Fruit extends Food {
public Fruit(String name1) {
super.name = name1;
}
}
class FastFood extends Food {
public FastFood(String name1) {
super.name = name1;
}
}
class Food {
public String name = null;
public Food() {
}
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving " + this.name);
}
}
class Solution1 {
public static void main(String[] args) throws java.lang.Exception {
FoodFactory myFoods = new FoodFactory();
Food food1 = myFoods.getFood("FastFood");
Food food2 = myFoods.getFood("Fruit");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: "
+ food1.getClass().getSuperclass().getName());// modification
food1.servesFood();
food2.servesFood();
}
}

Java creating objects within objects

I'm trying to create a Pizza menu. I have 3 classes,
PizzaBase (with get / set methods for the thickness of the base
[either thin or deeppan])
PizzaTopping, again with get / set methods
for the type of topping
Pizza, where my cost variable is stored and
used across the 3 classes using inheritance.
As a cost variable is used for the base, the topping and the overall pizza itself.
Now my question is this, how would I go about creating a Pizza object, which in turn creates 1 base object, and a few toppings objects, each with a price?
I can work out how to calculate an overall price, I'm just a bit stuck creating objects within objects.
public class PizzaTopping extends Pizza{
private String topping;
public String getTopping(){
return this.topping;
}
public void setTopping( String topping ){
this.topping = topping;
}
}
public class PizzaBase extends Pizza{
private String base;
public void setBase( String base ){
this.base = base;
}
public String getBase(){
return this.base;
}
}
public class Pizza {
private double cost;
public void setCost( double cost ){
this.cost = Math.abs(cost);
}
public double getCost(){
return this.cost;
}
public void makingPizza(){
PizzaBase b = new PizzaBase();
}
}
Replace the Pizza class with CostableItem class:
public class CostableItem {
private double cost;
public void setCost( double cost ){
this.cost = Math.abs(cost);
}
public double getCost(){
return this.cost;
}
}
Then extend it in both toppings and base:
public class PizzaBase extends CostableItem {...}
public class PizzaTopping extends CostableItem {...}
After that create a class called Pizza that has one base and multiple toppings:
public class Pizza{
private PizzaBase base;
private ArrayList<PizzaToppings> toppings;
//..
}
You don't need inheritance for this at all. At the most you might need an interface. So I would design it this way:
public interface PricedItem {
double getCost(); //double is suitable for our purposes
}
Since you want to calculate cost, everything that is a priced item should have a getCost() method. This will apply to your PizzaTopping, PizzaBase, and Pizza class:
public class PizzaTopping implements PricedItem
private String name;
private double cost;
public PizzaTopping(String name, double cost) {
this.name = name;
this.cost = cost;
}
...
#Override
public double getCost() {
return cost;
}
}
More or less the same thing for PizzaBase:
public class PizzaBase implements PricedItem {
private double cost;
...
}
Your Pizza class will also implement PricedItem. But what is also important is that you will have a collection of PizzaTopping instances; there is no inheritance here!
public class Pizza implements PricedItem {
private double cost;
private PizzaBase base;
private List<PizzaTopping> toppings;
public Pizza(double cost, PizzaBase base) {
this.cost = cost;
this.base = base;
toppings = new ArrayList<PizzaTopping>();
}
...
public void addTopping(PizzaTopping topping) {
//left as an exercise to the reader :)
}
#Override
public double getCost() {
//this is left as an exercise to the reader :)
return totalCost;
}
}

Categories