Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- //interface
- interface IPrice {
- public double calcPriceWithVAT();
- }
- //abstract class
- abstract class AbsItem implements IPrice {
- protected String itemId;
- protected String name;
- protected double unitPrice;
- protected int itemCount;
- public AbsItem(String itemId, String name, double unitPrice, int itemCount) {
- this.itemId = itemId;
- this.name = name;
- this.unitPrice = unitPrice;
- this.itemCount = itemCount;
- }
- public String toString() {
- return itemId + " " + name
- + " Unit Price:" + String.format(
- "%.2f",unitPrice)
- + " Item Count:" + itemCount;
- }
- }
- //FoodItem child class
- class FoodItem extends AbsItem {
- private Date expiryDate;
- private String countryOfOrigin;
- public FoodItem(String itemId, String name, double unitPrice, int itemCount, Date expiryDate,
- String countryOfOrigin) {
- super(itemId, name, unitPrice, itemCount);
- this.expiryDate = expiryDate;
- this.countryOfOrigin = countryOfOrigin;
- }
- public String toString() {
- return super.toString() + " Expiry date:" + expiryDate
- + " Country of origin: " + countryOfOrigin;
- }
- public double calcPriceWithVAT() {
- return (this.unitPrice * this.itemCount) +
- (this.unitPrice * this.itemCount * 0.05);
- }
- }
- class NonFoodItem extends AbsItem {
- private String itemCategory;
- public NonFoodItem(String itemId, String name, double unitPrice, int itemCount, String category) {
- super(itemId, name, unitPrice, itemCount);
- this.itemCategory = category;
- }
- public String toString() {
- return super.toString() + " category:" +itemCategory;
- }
- public double calcPriceWithVAT() {
- return (this.unitPrice * this.itemCount) +
- (this.unitPrice * this.itemCount * 0.025);
- }
- }
- public class AbsItemTester {
- public static void main(String[] args) {
- //Create a list of items
- List<AbsItem> items = new ArrayList<>();
- AbsItem foodItem1 = new FoodItem("F101", "Alpin Water", 10, 10, new Date("22/12/2023"), "Turkiye");
- AbsItem nonFoodItem1 = new NonFoodItem("KB11", "Keyboard", 20, 10, "Computer Equipment");
- //add items to the list
- items.add(foodItem1);
- items.add(nonFoodItem1);
- //iterate over the list using for-each loop
- //and print item, its subtotal
- double total = 0;
- for (AbsItem item : items) {
- System.out.println(item
- + "\n\tSubtotal:"
- + String.format("%.2f",item.calcPriceWithVAT()));
- total += item.calcPriceWithVAT();
- }
- //print total of all items in the list
- System.out.println("\nTotal price:" +total);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment