Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Delivering the MVP Defaulting Parameters

Challenge answer looks correct in Preview and my local console, but grader doesn't accept it.

My modified ShoppingCart.java writes out the correct result, but the same code in the the grader doesn't pass. Any ideas what's wrong? Thanks...

λ javac Example.java && java Example
Adding 5 of Cherry PEZ refill (12 pieces) to the cart.
Adding 1 Yoda PEZ dispenser to the cart.
Example.java
public class Example {

  public static void main(String[] args) {
    ShoppingCart cart = new ShoppingCart();
    Product pez = new Product("Cherry PEZ refill (12 pieces)");
    cart.addItem(pez, 5);
    Product dispenser = new Product("Yoda PEZ dispenser");
    cart.addItem(dispenser);
  }

}
ShoppingCart.java
public class ShoppingCart {

 public void addItem(Product item, int quantity) {
    System.out.printf("Adding %d of %s to the cart.%n", quantity, item.getName());
  }

  // new method with different signature
  public void addItem(Product item) {
    System.out.printf("Adding 1 %s to the cart.%n", item.getName());
  }
}
Product.java
public class Product {
  /* Other code omitted for clarity, but you could imagine
     it would store price, options like size and color
  */
  private String mName;

  public Product(String name) {
      mName = name;
  }

  public String getName() {
      return mName;
  }
}

1 Answer

Michael, they want you to overload the function without repeating any of the overloaded function's code block:

public class ShoppingCart {

 public void addItem(Product item, int quantity) {
    System.out.printf("Adding %d of %s to the cart.%n", quantity, item.getName());
  }

  // new method with different signature
  public void addItem(Product item) {
    addItem(item, 1);
  }
}

Thx very much... that's a more compact, recursive solution. A really interesting difference - extending the logic block of the original, instead of creating a new block.