Foor循环的子类打印

时间:2018-03-28 22:07:03

标签: java

子类打印 购物车

我正在制作一个购物车,我创建了一个3个子类,Food,Drink和Candy,它们都有不同的变量。并使用一个Product类(扩展)。在我的主类中,我添加了一个名为inventory的ArrayList。所以基础

private static ArrayList<Product> inventory = new ArrayList<Product>();

现在我被困在要在3个子类中打印特定产品详细信息的部分。我为所有3个子类创建了一个打印方法,但它只接受了仅用于product(extends)类的print方法。

private static void printProduct()
{
    for(Product f: inventory)
    {
        System.out.println(f.getProductId() + "\t" + f.getProductName() + "\t \t" + f.getPrice());
        System.out.println();
    }
    System.out.println("Please choose a Product by ID to view more Details");
    int chosenProduct = input.nextInt();
    for(Product p: inventory)
    {
        if (chosenProduct==p.getProductId())
        {
            p.
        }
    }
}

以下是一个子类的示例,我只是将printfood方法复制并粘贴到此类中以查看它是否可行。 (它没有)

public class Food extends Product{

private String brand;
private int protein;
private int carbs;
private int fats;


public Food()
{

}
public void printPoduct()
{
    System.out.println("Product ID:\t" + getProductId());
    System.out.println("Product Name:\t" + getProductName());
    System.out.println("Brand:\t" + brand);
    System.out.println("Quantity:\t" + getQuantity());
    System.out.println("Price:\t" + getPrice());
    System.out.println("");
    System.out.println("Calories:\t "+ getCalories());
    System.out.println("Carbohydrates: " + carbs);
    System.out.println("Protein:\t " + protein);
    System.out.println("Fats:\t " + fats );
}

继承产品类,这与库存Arraylist链接

public class Product implements Serializable{ 
private int productId;
private String productName;
private int quantity;
private double price;
private int calories;
private boolean inStock;
private static final long serialVersionUID= 1L; //Specify Version

public Product()
{

}
public void printPoduct()
{
    System.out.println("Product ID:\t" + getProductId());
    System.out.println("Product Name:\t" + getProductName());
    System.out.println("Brand:\t" + brand);
    System.out.println("Quantity:\t" + getQuantity());
    System.out.println("Price:\t" + getPrice());
    System.out.println("");
    System.out.println("Calories:\t "+ getCalories());
    System.out.println("Carbohydrates: " + carbs);
    System.out.println("Protein:\t " + protein);
    System.out.println("Fats:\t " + fats);




}

0 个答案:

没有答案