Java Java Objects Harnessing the Power of Objects Filling the Dispenser

Tomas Svojanovsky
Tomas Svojanovsky
24,500 Points

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.