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) Meet Objects Privacy and Methods

Why are we making a new instance of the class 'PezDispenser' called dispenser? Why not use the PezDispenser directly?

or is there any benifits of using the instances?

2 Answers

Stone Preston
Stone Preston
42,016 Points

What if we wanted to make several different PezDispensers?

Classes act as a general blueprint of what an object should look like. Then, by creating instances of that class, we can create non-general objects of that class with attributes that are unique to each object

We could have a Darth Vader pez dispenser, a Luke Skywalker pez dispenser and a Han Solo pez dispenser. They all share the same properties and methods of the PezDispenser class, but they are each different instances with different values for their properties. They are unique, and by creating each one as a new instance of Pez dispenser, we can treat them as such.

Besides that, the methods and properties defined in the PezDispenser class are instance methods and properties. This means they act on instances of a class, not the class itself. In order to just use the class without ever creating an instance we would have to make the methods and properties static

That makes sense. Thanks Stone Preston !