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 Harnessing the Power of Objects Constants

Zachary Martin
Zachary Martin
3,545 Points

Creating in instants of MAX_PEZ question

When he called MAX_PEZ why was it called as PezDispenser.MAX_PEZ instead of dispenser.MAX_PEZ? is it not an object?

1 Answer

Ben Reynolds
Ben Reynolds
35,170 Points

He was only able to do that after he made MAX_PEZ static. Static members of a class don't need an instance to be created first before they're accessed, so you can just use the name of the class itself. To work with any of the non-static members (other fields, methods etc that don't have the static keyword) then you'd need to create an instance first. Further down in his code he does access some of those other members though, such as the getCharacterName method. That's where the "dispenser" instance comes in.

For example when you use something like Math.random(), you don't have to say Math math = new Math() first, you can just call random() right after the class name. This only works because the random() method is static.