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.
Safira Nugroho3,910 Points
Why "new PezDispenser()"?
So I understand that PezDispenser is the variable type and dispenser is the variable itself, but what does Craig mean when he says "We're gonna make a brand new PezDispenser"? I don't see "PezDispenser()" being used anywhere in Example.java, so I'm really having trouble understanding what that particular line does.
Hi Safira Nugroho,
In Java you have primitive types like int, float, double for example and types of reference to an object.
In order to create an object you have to create an instance of the specific class from which you want to create an object of. That may sound very complicated but it is pretty simple.
// declaration of a variable int number; // initialisation if the variable number number = 5; /****************************************************/ // declaration of a variable PezDispenser myOwn; // initialisation of the variable myOwn myOwn = new PezDispenser();
Those lines above could of course be shortened:
// declaration + initialisation int number = 5; PezDispenser myOwn = new PezDispenser();
But I think you can understand the process better with the first example. Like you see, you can initialise primitive types without the keyword
new. For types which reference to an object you have to use the keyword
new and call the constructor of that class which in this case is
With the declaration of the variable you only let the compiler know that you have created a variable of a chosen type but it doesn't hold any real value with that step. It will hold a default value which is
null and basically means it holds nothing.
Only with the initialisation your variable will represent a real value or object.
Hope I could help you out there a little bit. If you still have questions please don't hesitate to ask.