简体   繁体   中英

How do I add objects inside an ArrayList using oop?

I have classes "BaseProduct" - abstract, "Food" - implements BaseProduct and a "Cart" which puts many foods inside.

So how do I put the foods inside the Cart and how do I go about adding their expiration date discount(5 days before their expiration date, they get discounted with 10%)?

I should also Create a class "Cashier" that has a method to print a receipt. The method accepts a "Cart" (collection of products) and the date and time of purchase. It should print all purchased products with their price, quantity, the total sum and the total discount. Would be greatly thankful if someone helps.

Class BaseProduct looks like this:

public abstract class BaseProduct {

    private String name;
    private String brand;
    private Double price;

    protected BaseProduct(String name, String brand, Double price) {
        this.name = name;
        this.brand = brand;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Class Food looks like this :

package Products.PerishableProducts;

import Products.BaseProduct;

import java.util.Date;

public class Food extends BaseProduct {

    private Date expirationDate;
    //sample date - 2020/04/20 -> yyyy-MM-dd
    //TODO:CHECK WHETHER OR NOT YOU HAVE EXPIRATION DATE DISCOUNTS WHEN ADDING ITEMS IN CART


    public Food(String name, String brand, Double price, Date expirationDate) {
        super(name, brand, price);
        this.expirationDate = expirationDate;

    }

    public Date getExpirationDate() {
        return expirationDate;
    }

    public void setExpirationDate(Date expirationDate) {
        this.expirationDate = expirationDate;
    }
    }

Class "Cart"(shopping cart) looks like this:

package Cart;

import Products.BaseProduct;
import java.util.List;

public class Cart {

 private static List<BaseProduct> products;


    //TODO:add products
    public List<BaseProduct> add(List<BaseProduct> products){
      
    }


    //TODO: remove products
}

To add products to the cart Finish writing the Cart::add method. Initializing the products list will help. Then have a look at the add methods on the list implementation you chose .

To apply a discount. Overload the getPrice method in Food with a getprice(Date purchaseDate) method. return the price from super.getPrice() less your discount when appropriate. You may find that having a getDiscount(Date purchaseDate) method is useful, as the Cashier class wants a total discount.

  1. Why is your products list static?

  2. To initialize the list there are two things you can do:

a. Eager initialization:

private List<BaseProduct> products = new ArrayList<>();
public void add(BaseProduct product) {
    this.products.add(product);
}

b.Lazy Initialization:

public void add(BaseProduct product) {
    if (this.products == null) {
        this.products = new ArrayList<>();
    }
    this.products.add(product);
}

Let me know if this answers your question or you have any other query.

There can be multiple approaches to solve this problem. If we think about where would it count to have a discount is obviously when we calculate the price of a product. So I would refactor the Food class as follows:

import java.time.LocalDate;

public class Food extends BaseProduct {

    // Use LocalDate instead of the outdated Date class. It is way easier to use and to avoid some common pitfalls
    private LocalDate expirationDate;

    public Food(String name, String brand, Double price, LocalDate expirationDate) {
        super(name, brand, price);
        this.expirationDate = expirationDate;
    }

    public LocalDate getExpirationDate() {
        return expirationDate;
    }

    public void setExpirationDate(LocalDate expirationDate) {
        this.expirationDate = expirationDate;
    }

    // Override the calculation of the price of a Food product and apply the discount
    @Override
    public Double getPrice() {
        return super.getPrice() * (1.0 - getDiscount());
    }

    // Calculate the discount percentage. If the expiration day is less than 5 days compared to current day, return a 10% discount, otherwise return 0
    private Double getDiscount() {
        return expirationDate.minusDays(5).isAfter(LocalDate.now()) ? 0.0 : 0.1;
    }

}

Now, in case of a Cart we probably care about the total price of how much a client would want to pay. So we can write the following methods:

import java.util.ArrayList;
import java.util.List;

public class Cart {
    List<BaseProduct> products = new ArrayList<>();

    public void addProduct(BaseProduct product) {
        products.add(product);
    }

    // Returns the total price of the items currently in our cart. Discount is applied to the items which are eligible
    public Double getTotalPrice() {
        return products.stream().mapToDouble(BaseProduct::getPrice).sum();
    }
}

We can use the Cart and in the following way:

    public static void main(String[] args) {
        BaseProduct cheese = new Food("cheese", "CheeseBrand", 10.0, LocalDate.of(2021, 10, 1));
        BaseProduct vine = new Food("vine", "Vine", 50.0, LocalDate.of(2025, 12, 1));

        Cart cart = new Cart();
        cart.addProduct(cheese);
        cart.addProduct(vine);

        System.out.println(cart.getTotalPrice());
    }

Assuming that the current date is: 2021 31th of October, we would get the following total amount for the example above: 59.0 . Also, we may want to think about what would happen if there is an expired product. For now, we apply a 10% discount to it, we probably would not want to be able to put the item into the cart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM