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

pratham daswani
pratham daswani
979 Points

how to use default parameters in a method

here i need to use a different method signature and thats what i did , but in the process i am repeating myself and they are asking to use the default parameter , how to use the default parameter in the same method?

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);
    /* Since a quantity of 1 is such a common argument when adding a product to the cart,
     * your fellow developers have asked you to make the following code work, as well as keeping
     * the ability to add a product and a quantity.
     */
    Product dispenser = new Product("Yoda PEZ dispenser");
    /* Uncomment the line following this comment,
       after adding a new method using method signatures,
       to solve their request in ShoppingCart.java
    */
    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());
    /* Other code omitted for clarity. Please imagine
       lots and lots of code here. Don't repeat it. 
    */
  }

  public void addItem(Product item)
  {
    System.out.printf("Adding 1 of %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

pratham, you need to override the add() method so it takes only an item, rather than an item and a quantity.

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

So with this you have a 2nd add method, with a different method signature, that takes an item, and then, rather than repeat any of the other add() method's code, just calls it with the item and the quantity 1.

This is a very common pattern, and it keeps your code DRY.