购物车子类打印问题:如何输出子类特定产品详情
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
Define a Print Contract in the Product Base Class
First, add an abstractprintmethod to yourProductclass. 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(); }Override print() in Each Subclass
Update yourFood,Drink, andCandyclasses to override theprintmethod (use the@Overrideannotation 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"); } }Print Inventory with Polymorphism
Now in your main class, simply loop through theinventoryand callprint()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
@Overridewhen overriding methods—it tells the compiler to verify you're actually overriding a base class method (prevents typos likePrint()instead ofprint()). - Make sure you're adding subclass instances to
inventory(notProductinstances, which you can't do anyway ifProductis abstract).
内容的提问来源于stack exchange,提问作者Carl Peralta

