Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
PezDispenzer dispenzer = new PezDispenzer(); Why do we use "New"?
Why do we use the parameter New although the class is already clearly defined?
You use new (not New) to create objects. PezDispenser is a class. If you want PezDispenser objects (instances of the class) you need to create them. Here we create two of them:
PezDispenser pd1 = new PezDispenser(); PezDispenser pd2 = new PezDispenser();
Here I'm assuming the PezDispenser constructor doesn't expect any parameters.
Take another example. If you have a Student class, you don't have any Student objects until you create them using new:
Student jose = new Student("Jose"); Student bill = new Student("Bill"); Student maria = new Student("Maria");
Here I'm assuming that the Student constructor requires a name.
Now there are three Student objects, or 3 instances of the Student class.
Remember, Java is case-sensitive, so new and New are different.
Carlos Federico Puebla Larregle21,073 Points
The keyword "new" is not a parameter is an operator and you have to "postfix" to the "new" operator a call to the constructor in this case "PezDispenzer();". The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, in this case the variable "dispenzer" of type "PezDispenzer".
I hope that helps a little bit.
Jon Sultana6,916 Points
The new keyword I am assuming is used for Dynamic memory allocation. I am a former C++ student and we would use the new keyword whenever we wanted to dynamically allocate memory in the heap. Once the program ends or the object goes out of scope the memory is released back to the free store. So what it seems like you are doing is creating two new PezDispenser objects dynamically by calling the default object constructor that you do not see because the compiler takes care of it for you"PezDispenser()".