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 trialRichard Gagain
404 PointsPezDispenser dispenser = new PezDispenser(); explanation
Can someone explain to me what each word here means in relation to creating this object? I'm trying to wrap my head around what exactly is being done here. I get that we are creating an object called dispenser and it's pulling in the PezDispener class but I don't really understand how.
2 Answers
Fatemah Tavakoli
13,797 PointsHi Richard,
In this code you are creating an instance of type PezDispenser. You have the PezDispenser class and you want to use it as a structure of the dispenser object. I look at it in this way: as if you are creating a string variable. you want to create a new variable with specific structure that is been defined in PezDispenser class. "PezDispenser dispenser " this part we are just referencing to the PezDispenser class, but we still do not have created the object. in order to create that we use "new PezDispenser()". The dispenser object needs to be assign to the PezDispenser class before we use it.
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsIn addition to fatima Tavakoli explanation imagine instead of PezDispenser you have a Car class and you want to create various instances (in this case Car Models) of Car Class. You will do something like this:
Car mercedes = new Car();
Car toyota = new Car();
Car lamborghini = new Car();
*Class Car * provides the blueprint for other Car objects . mercedes, toyota and lamborgini are all instances of the Car Class.
The new keyword is used to instantiate the Car object.
Car() refers to the Car Class constructor; in this case the Car class constructor is empty and doesn't take paramenters.
All these also applies to PezDispenser class