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

2 Answers

Hi Jinhwa,

In this challenge you are creating a new method that is called the same as an existing one, addItem.

The difference is that the method you are creating has a different method signature; in this case, the number of parameters are different. The existing addItem method receives a Product and a quantity. It then adds quantity of Product into your ShoppingCart. The new method just receives a Product as it will always just add one of that Product to your cart.

The line of code that needs to work is:

cart.addItem(dispenser);

As you can see, this doesn't fit the existing addItem method, which takes two parameters:

  public void addItem(Product item, int quantity) { // two parameters
    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. 
    */
  }

The existing addItem method has lots of code hidden - we don't want to be duplicating any of that. But we need to change something so that it takes only one parameter. The existing method remains a requirement; we can't delete it as it is needed for instance where multiple items are added to the cart.

The new method takes a single parameter, an instance of Product and results in one of that product being added to the cart. The method signature takes one parameter:

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

Inside that method, we call the existing addItem method but default the quantity to 1.

Now, if you've uncommented the line in Example.java your code should work.

I hope that helps.

Steve.

Oskar Selberg
Oskar Selberg
1,948 Points

Help is on the way, stay safe <3