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 trialTomas Svojanovsky
26,680 PointsWhy 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;
}
1 Answer
gregsmith5
32,615 PointsI 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.
Gonçalo Palma
9,121 PointsGonçalo Palma
9,121 PointsThe 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.