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!
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
Einar Mikalsen5,281 Points
Not sure if I understand new PezDispenser
This may seem incredibly stupid, but I have understood this correctly.
PezDispenser dispenser = new PezDispenser();
"In the PezDispenser file there is a class called PezDispenser and from this class we want to create a new object called dispenser"
Brendon Butler4,254 Points
There are four main parts to this line. You start off by telling the compiler what type of object you have. In this case, it's a PezDispenser object.
The next part is an identifier for your object. A way for you to reference and manipulate it. In this case, it's called "dispenser." You could name it whatever you want. For example, it could be "pezDispenser," "yoda," etc. As long as it makes sense to you and anyone that may read your code.
Then, you can either end the line here with a colon or set the value of new variable you've created. Here, we're creating a new instance of the object. So you'd add "new" for a new instance.
Lastly, you want to reference the class name and its constructor. In this case, it would be PezDispenser().
Here are some examples
// creating a new instance of a PezDispenser. PezDispenser dispenser = new PezDispenser(); // duplicating an existing instance of a PezDispenser PezDispenser dispenser2 = dispenser; /* Using one of these dispensers you must use the variable name as a reference to the PezDispenser instance */ dispenser.dispense(); // you'll see this in a later tutorial.
Hopefully this helps, I wrote it pretty quickly. Happy coding!
Mladen Jovanovic4,662 Points
Quick question, here, though: couldn't he have just stated that a PezDispenser object exists and that it's named "dispenser", without specifying that it's a new PezDispenser object?
Basically, what I'm saying is, would just writing "PezDispenser dispenser;" be different than writing "PezDispenser dispenser = new PezDispenser();"?