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

Why not just use "private" for MAX_PEZ instead of using "final"?

I see that the Craig wanted to make sure that the maximum number of Pezs to be 12 and he wanted to make sure that no one can change it later. So why did he uses the keyword "final" to the code instead of just setting it to private by using the "private" keyword?

1 Answer

Hi there,

The final keyword only allows a value to be assigned to that variable/constant once. That way, given that an integer is assigned in MAX_PEZ, the contents of that constant can not be altered.

The same cannot be said of a member variable of private access. You can use setter methods from within the class to alter the value of that variable.

Note that the final keyword makes the constant point to an instance of something, in this case an integer. If the the value of that instance changes, so will the contents of the "constant". Since 12 isn't going to change value, that's not relevant here!

Steve.