java - Using superclass method to calculate price -
i doing problem on inheritance , hierarchy of classes. problem this: have superclass contains quantity attribute. code class here:
class items { private int quantity; public items(int quantity) { this.quantity = quantity; }
then have 2 subclasses contains prices , other attributes. code snippet:
class coffee extends items { private string size; public coffee (int quantity, string size) { super(quantity); this.size = size; } } class donuts extends items { private double price; private string flavour; public donuts(int quantity, double price, string flavour) { super(quantity); this.price = price; this.flavour = flavour; } }
what want calculate total price each object.
my program reads text file , creates object , stores them in arraylist. text file reading this, please note have commented first 2 lines explain each token is, not included in real file.:
coffee,3,medium // name of item quantity , size
donut,7,0.89,chocolate // name quantity price flavor
donut,3,1.19,eclair
coffee,1,large
i want calculate total price without duplication of code. have done far in superclass this:
public double totalprice(items x) { double total = 0; if(x instanceof coffee) { total = getquantity() * getsizeprice(); } else { if (x instanceof donuts) { total = totalprice(); } } return total; } public abstract string getsizeprice();
in coffee
subclass:
public double getsizeprice() { double pricesmall = 1.39; double pricemed = 1.69; double pricelar = 1.99; if(size == "small") { return pricesmall; } else { if (size == "medium" ) { return pricemed; } } return pricelar; }
i believe going in circles 1 wondering if community guide me in right direction. if question confusing, feel free ask , explain further. possible totalprice()
method in each class , through ploymorphism class calculates price of items in main method.
Comments
Post a Comment