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) Harnessing the Power of Objects Method Signatures

PezDispenser load method

In the video you created the load with the given parameter (int pezAmount). Can you explain this a bit more? Why use pezAmount? what was the purpose of creating this second load method? what is it supposed to do? I think I am thrown off by the concept, because there are two methods with the exact same method name, so I am a little lost. Thank you!

1 Answer

The first load() method takes no parameters (as you can see, the parentheses are empty), and loads the max number. But what if you want to load less than the max?

Craig's solution is to write a second load() method, but this time he gives it an int parameter: the number of pez you want to load. The name of the parameter is not important. You can name it anything you want: numPez, numberOfPez, pezAmount, amountOfPez, x, y, hello, etc. But best practices say the name should be meaningful, and pezAmount is therefore better than x or y or hello. Technically it is just the name of an int variable. So to load 6 pez you would write:


Having several methods with the same name in the same class with different method signatures, i.e., different number or type of parameters, is called overloading. A good example is the class that contains println(). There is also a println(int x), a println(double x), println(String s), println(boolean y), etc.

Once he has a method that will take any given number, Craig refactored the first one to call the second with MAX_PEZ, which is a number. This in an example of the DRY principle: not repeating the code in load(int x) in load().