如何重置构造函数的Getters和Setters?Java作业产品信息修改求助
Hey Nick, let's work through how to properly implement this task using getters/setters and meet your requirement of updating product information shared across classes. First, let's fix some obvious issues in your current code, then refactor the solution step by step.
1. 先修正代码中的拼写与逻辑错误
Your code has a few small but critical bugs that need fixing first:
- 拼写错误:
setDescripption→setDescription(extra 'p'); constructor parameterexpiarayDate→expiaryDate(matches the member variable name); for consistency, I'd recommend renaming date fields toexpiryDate(standard English spelling) - LocalDate comparison error: In
verifyExpireProduct, comparingLocalDateobjects with==checks reference equality, not value equality. Useequals()instead, and add null checks to avoid NPEs:public void verifyExpireProduct() { if(expireDate != null && expireDate.equals(expiaryDate)) { System.out.println("Product is expired"); } else { System.out.println("Product is not expired"); } } - LocalDate.of parameter order: In
setExpireDate,LocalDate.of(day, month, year)is backwards—this method takes(year, month, dayOfMonth)as arguments. Fix it to avoid invalid dates:LocalDate date = LocalDate.of(year, month, day);
2. 正确使用Getters和Setters重构editProductInformation
Your current method hardcodes values directly into member variables, which breaks encapsulation and isn't flexible. Instead, use setter methods to modify values, and make the method support dynamic input (either via parameters or user input):
方案一:Dynamic update via method parameters (great for programmatic/batch changes)
public void editProductInformation(int newId, String newDescription, double newRecommendedPrice, int newUnit, double newWeight) { // Use setters instead of direct member access to follow encapsulation principles setID(newId); setDescription(newDescription); setRecommendedUnitPrice(newRecommendedPrice); setUnit(newUnit); setWeight(newWeight); }
方案二:Interactive update via user input (for manual edits)
public void editProductInformation() { System.out.println("=== Editing Product Information ==="); System.out.print("Enter new product ID: "); int newId = input.nextInt(); input.nextLine(); // Clear the newline from the input buffer System.out.print("Enter new product description: "); String newDescription = input.nextLine(); System.out.print("Enter new recommended unit price: "); double newPrice = input.nextDouble(); System.out.print("Enter new unit count: "); int newUnit = input.nextInt(); System.out.print("Enter new weight: "); double newWeight = input.nextDouble(); // Use setters to apply changes setID(newId); setDescription(newDescription); setRecommendedUnitPrice(newPrice); setUnit(newUnit); setWeight(newWeight); System.out.println("Product information updated successfully!"); }
3. 实现"所有类共享产品主要信息"的需求
If your goal is to have all instances of the Product class share the same ID, description, etc., you'll need to mark these fields as static (so they belong to the class, not individual instances) and update your getters/setters to be static methods:
Step 1: Make shared fields static
protected static int ID; protected static String description; protected static double recommendedUnitPrice; protected static int Unit = 1; protected static double weight; // Keep non-shared fields (like expiry dates) as non-static protected LocalDate expiryDate; protected LocalDate expireDate;
Step 2: Update getters/setters to static methods
public static int getID() { return ID; } public static void setID(int newId) { ID = newId; } public static String getDescription() { return description; } public static void setDescription(String newDescription) { description = newDescription; } // Repeat for other static fields
Step 3: Refactor the edit method for static fields
You can make the edit method static too, so you don't need an instance to call it:
public static void editSharedProductInformation(int newId, String newDescription, double newRecommendedPrice, int newUnit, double newWeight) { setID(newId); setDescription(newDescription); setRecommendedUnitPrice(newRecommendedPrice); setUnit(newUnit); setWeight(newWeight); }
Now, any changes made via this method will be reflected across all Product instances, since they share the static fields.
4. Extra Optimization Tips
- Add input validation to setters: Ensure data integrity by checking values before assigning them, e.g.:
public void setID(int newId) { if (newId > 0) { this.ID = newId; } else { throw new IllegalArgumentException("Product ID must be a positive number"); } } - Clean up Scanner resources: Since your Scanner is a member variable, call
input.close()when you're done using it to avoid resource leaks. - Clarify date field names: Rename
expiaryDateandexpireDateto something more descriptive (likemanufacturerExpiryDateandstoreExpiryDate) to avoid confusion.
内容的提问来源于stack exchange,提问作者Nick Jam

