Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Delivering the MVP Defaulting Parameters

Not sure how to pass this quiz

I am stuck with this error: " Hmmm, seems like you shouldn't repeat yourself, why don't you try calling the original addItem method with the default parameter of 1. "

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()); 
  }
   public void addItem(Product item) {
   System.out.printf("Adding 1 of %s to the cart.%n", item.getName()); }
}
Product.java
public class Product {
  private String mName;
  public Product(String name) {
      mName = name;
  } public String getName() {
      return mName; }  
}

I think it has something to do with the

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

// and

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

1 Answer

Will Canniford
Will Canniford
4,116 Points

When creating the one that takes 1 as the default quantity, you should call the original method and place one as the quantity. Then if someone was to call the method with just an item then 1 of that item would be automatically assumed and taken as the default value.

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

does that make sense?

Steve Gardner
Steve Gardner
17,786 Points

Exactly, all you need is:

public void addItem(Product item) {
  addItem(item, 1);
}

That's all. No need to call System.out.printf here. It's taken care of in the original implementation of the method, which you just called.

You could have any number of method signatures for addItem() that can reuse one another depending on the context. Yay polymorphism.