You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java多态购物车项目问题:静态ArrayList访问、类型判断及排序困惑

Java Shopping Cart Polymorphism Issues: Solutions to Your 3 Questions

Hey there! Let's break down each of your questions with practical fixes and explanations using your existing codebase.


1. Accessing ArrayLists from Static Methods (Fixing the "no access" error)

The problem here is that your perishables and nonPerishables lists are local variables inside the main method—static methods like sortItems and displayItems can't access local variables from another method. Since the project specifies using static ArrayLists, you need to declare them as static class members instead of main-local variables.

Fix:

Move the ArrayList declarations outside of main, at the class level, and mark them as static:

import java.util.ArrayList;
public class ShoppingCart {
    // Declare static lists at the class level so all static methods can access them
    static ArrayList<Perishable> perishables = new ArrayList<Perishable>();
    static ArrayList<NonPerishable> nonPerishables = new ArrayList<NonPerishable>();

    public static void main(String args[]) {
        // Remove the ArrayList declarations from here—they're now class-static
        Cereal cereal = new Cereal();
        // ... rest of your main code stays the same
    }

    static void sortItems(GroceryItem item){
        if(item instanceof Perishable)
            perishables.add((Perishable) item); // Add explicit cast to avoid compiler warnings
        if(item instanceof NonPerishable)
            nonPerishables.add((NonPerishable) item); // Cast here too
    }

    // ... rest of your methods
}

Now sortItems and displayItems can access the lists directly because they're static members of the same class. The explicit casts are needed because item is a GroceryItem reference, and we need to tell the compiler we're sure it's a subtype of Perishable/NonPerishable.


2. Distinguishing between Fruit and Meat (Subtypes of Perishable)

To check if a Perishable instance is a Meat or Fruit, you can use the instanceof keyword just like you did for Perishable/NonPerishable. This works because instanceof checks if an object is an instance of a specific class (or its subtypes).

Example in the displayItems method:

static void displayItems() {
    System.out.println("Here is the list of your Shopping Cart:\n--------------------------");
    System.out.println("Perishables:\n----");
    for(Perishable item : perishables) {
        if(item instanceof Meat) {
            Meat meatItem = (Meat) item; // Cast to Meat to access meat-specific methods
            System.out.println(meatItem.getDescription() + 
                ", Weight: " + meatItem.getWeightInPounds() + "lbs" +
                ", total price:" + meatItem.getTotalPrice());
        } else if(item instanceof Fruit) {
            Fruit fruitItem = (Fruit) item; // Cast to Fruit for fruit-specific methods
            System.out.println(fruitItem.getDescription() + 
                ", total price:" + fruitItem.getTotalPrice());
        }
    }
    // ... rest of your non-perishable display code
}

This lets you access subclass-specific methods (like getWeightInPounds() for Meat) that aren't defined in the parent Perishable class.


3. What Does "Sort Items and Add to ArrayList" Mean?

Looking at your comment for the sortItems method:

This function will be to take the item passed in and sort and add the item into one of the of Perishable or NonPerishable ArrayList. Use casting and/or the instanceof keyword to determine which list the item should be added to.

The wording here is a bit confusing—"sort" in this context means categorize, not sorting by price or name. The goal is to route each item to the correct list (Perishable vs NonPerishable) based on its type.

If the project did mean actual sorting (like ordering items by price), you'd need to:

  1. Make your GroceryItem class implement the Comparable interface, overriding compareTo() to define sorting logic (e.g., by total price).
  2. After adding items to the lists, call Collections.sort(perishables) and Collections.sort(nonPerishables).

But based on the instruction to use instanceof to pick the list, the intended meaning is definitely categorizing items into the correct list, not sorting them alphabetically/by price.


Full Modified Code (Putting It All Together)

import java.util.ArrayList;
public class ShoppingCart {
    static ArrayList<Perishable> perishables = new ArrayList<Perishable>();
    static ArrayList<NonPerishable> nonPerishables = new ArrayList<NonPerishable>();

    public static void main(String args[]) {
        Cereal cereal = new Cereal();
        cereal.setBrandName("Kellogs");
        cereal.setManufacturer("Sereal Manufacturing Co.");
        cereal.setUnitPrice(12.79);

        CannedSoup soup = new CannedSoup();
        soup.setSoupMaker("TastySoups Co.");
        soup.setDescription("Mushroom soup with natural flavors...");
        soup.setUnitPrice(2.39);

        Meat meat = new Meat();
        meat.setWeightInPounds(1.29);
        meat.setDescription("T-Bone Steak");
        meat.setPricePerPound(10.89);

        Fruit fruit = new Fruit();
        fruit.setDescription("Bananas imported from Brazil.");
        fruit.setPricePerBag(6.99);

        System.out.println("Price of " + meat.getDescription() + " is:" + meat.getTotalPrice());
        System.out.println("Price of " + fruit.getDescription() + " is:" + fruit.getTotalPrice());

        sortItems(cereal);
        sortItems(soup);
        sortItems(meat);
        sortItems(fruit);

        displayItems();
    }

    static void sortItems(GroceryItem item){
        if(item instanceof Perishable)
            perishables.add((Perishable) item);
        if(item instanceof NonPerishable)
            nonPerishables.add((NonPerishable) item);
    }

    static void displayItems() {
        System.out.println("Here is the list of your Shopping Cart:\n--------------------------");
        System.out.println("Perishables:\n----");
        for(Perishable item : perishables) {
            if(item instanceof Meat) {
                Meat meat = (Meat) item;
                System.out.println(meat.getDescription() + ", Weight: " + meat.getWeightInPounds() + "lbs, total price:" + meat.getTotalPrice());
            } else if(item instanceof Fruit) {
                Fruit fruit = (Fruit) item;
                System.out.println(fruit.getDescription() + ", total price:" + fruit.getTotalPrice());
            }
        }
        System.out.println("NonPerishables:\n----");
        for(NonPerishable item : nonPerishables) {
            if(item instanceof CannedSoup) {
                CannedSoup soup = (CannedSoup) item;
                System.out.println(soup.getDescription() + " by " + soup.getSoupMaker() + ", unitPrice:" + soup.getUnitPrice() + " totalPrice:" + soup.getTotalPrice());
            } else if(item instanceof Cereal) {
                Cereal cereal = (Cereal) item;
                System.out.println(cereal.getBrandName() + " by " + cereal.getManufacturer() + ", unitPrice:" + cereal.getUnitPrice() + " totalPrice:" + cereal.getTotalPrice());
            }
        }
    }
}

Note: I also fixed the non-perishable display logic to use instanceof instead of checking for getSoupMaker() (which would cause a compiler error if the item is a Cereal, since Cereal doesn't have that method).


内容的提问来源于stack exchange,提问作者user9629128

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:27:41