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

Matthew Kang
Matthew Kang
1,140 Points

Why do you put mPezCount = 0 in the constructor?

public class PezDispenser { public static final int MAX_PEZ = 12; private String mCharacterName; private int mPezCount;

public PezDispenser(String characterName) { mCharacterName = characterName; mPezCount = 0; //Why do you put this here }

public void load() { mPezCount = MAX_PEZ; }

public String getCharacterName() { return mCharacterName; } }

3 Answers

Aditya Sheode
Aditya Sheode
1,291 Points

He Just took a fresh pez dispenser like one you do at the market. SO like in the market it will be empty hence mPezCount = 0

Constructor is generally used to initialize the variables in class to the default number. Whenever the class is called the variable mPezCount will be intialized to 0. So that we can modify the value using member functions according to our requirments.

Joshua Mclendon
Joshua Mclendon
46,708 Points

I think he does it because say you want to create more than one PezDispenser well when you do your object creation PezDispenser pezOne = new PezDispenser(Luke) and then do a second one PezDispenser pezTwo = new PezDispenser(Yoda). Whatever methods you used to change the count for pezOne (like load() method) when you want to make pezTwo the count gets reset to zero because in the constructor it's set to 0 so that pezTwo doesn't get the amount of pez pezOne has.

Hope this helps

Best,

-JM