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 Filling the Dispenser

Why set a value in constructor?

Why Craig set the value of pezCount in constructor? Why did he not simply use

private int pezCount = 0;

instead of

public PezDispenser(String characterName) {
   this.characterName = characterName;
   pezCount = 0;
}
Gonçalo Palma
Gonçalo Palma
9,121 Points

The way I see it: see the constructor as a blank page for each object. It's in there that you initialize each of the new variables.

Furthermore, many programmers tend to first declare the variables and then initialize them later.

1 Answer

I think the reason is just to reinforce the idea of using the constructor. Code written for lessons is often written for the sake of instruction at the expense of good practice, but in this case it's a matter of style. Some programmers initialize everything in the constructor, others prefer to initialize when the fields are declared. Which you use is ultimately up to you (or your boss), but keep in mind that you'll sometimes need to write more than one constructor for your class, and each one may need to change the value of one or more member fields. In that case, you may want to set the value in all of your constructors, even if it's the same for most of them, to clearly communicate your intentions. Again, that's just a matter of style.