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

购物车子类打印问题:如何输出子类特定产品详情

Hey Carl, let's work through your shopping cart product printing issue—sounds like a classic case of getting polymorphism to work right for your subclass details!

The Core Issue

Since your inventory is an ArrayList<Product>, when you loop through it, the compiler sees each item as a Product instance. If your base class doesn't define a common print method that subclasses override, the JVM can't trigger the subclass-specific print logic you wrote.

Step-by-Step Fix

  1. Define a Print Contract in the Product Base Class
    First, add an abstract print method to your Product class. This forces all subclasses to implement their own version, and ensures polymorphism works as expected:

    public abstract class Product {
        // Shared properties (e.g., name, price)
        protected String name;
        protected double price;
    
        public Product(String name, double price) {
            this.name = name;
            this.price = price;
        }
    
        // Abstract method: all subclasses must implement this
        public abstract void print();
    }
    
  2. Override print() in Each Subclass
    Update your Food, Drink, and Candy classes to override the print method (use the @Override annotation to catch mistakes early!) and output their unique variables:

    public class Food extends Product {
        private String expirationDate;
    
        public Food(String name, double price, String expirationDate) {
            super(name, price);
            this.expirationDate = expirationDate;
        }
    
        @Override
        public void print() {
            System.out.printf("Food | Name: %s | Price: $%.2f | Expires: %s%n", 
                name, price, expirationDate);
        }
    }
    
    public class Drink extends Product {
        private double volumeLiters;
    
        public Drink(String name, double price, double volumeLiters) {
            super(name, price);
            this.volumeLiters = volumeLiters;
        }
    
        @Override
        public void print() {
            System.out.printf("Drink | Name: %s | Price: $%.2f | Volume: %.1fL%n", 
                name, price, volumeLiters);
        }
    }
    
    public class Candy extends Product {
        private boolean isSugarFree;
    
        public Candy(String name, double price, boolean isSugarFree) {
            super(name, price);
            this.isSugarFree = isSugarFree;
        }
    
        @Override
        public void print() {
            System.out.printf("Candy | Name: %s | Price: $%.2f | Sugar-Free: %s%n", 
                name, price, isSugarFree ? "Yes" : "No");
        }
    }
    
  3. Print Inventory with Polymorphism
    Now in your main class, simply loop through the inventory and call print() on each item. The JVM will automatically use the subclass's implementation:

    public class ShoppingCartMain {
        private static ArrayList<Product> inventory = new ArrayList<>();
    
        public static void main(String[] args) {
            // Populate inventory with subclass instances
            inventory.add(new Food("Organic Apple", 1.99, "2024-12-31"));
            inventory.add(new Drink("Cola", 2.49, 1.5));
            inventory.add(new Candy("Gummy Bears", 3.99, false));
    
            // Print all product details
            System.out.println("=== Inventory Details ===");
            for (Product item : inventory) {
                item.print(); // Triggers the correct subclass print method!
            }
        }
    }
    

Quick Checks to Avoid Headaches

  • Always use @Override when overriding methods—it tells the compiler to verify you're actually overriding a base class method (prevents typos like Print() instead of print()).
  • Make sure you're adding subclass instances to inventory (not Product instances, which you can't do anyway if Product is abstract).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:41:23