Java Java Objects Harnessing the Power of Objects Filling the Dispenser

Private or final? When to use where?

In this video pezCount is declared as private and Craig says at 00.32 that lets make it private so that no one could change it. But we can make it final instead. Then when to use what?

1 Answer

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 84,579 Points

private and final are dealing with different kinds of things. You could use them both together, one or the other, or none at all.

private is an access modifier. We set something to private if we only want it accessed from within the class. This is to prevent bugs and keep your code clean by only giving access to certain behaviors if needed. If other classes don't have to directly access this property, don't expose it to them.

final is a keyword that says this property will never change, it will never be reassigned. If you know this value should never change, it's a good idea to say it's final so that someone doesn't accidentally change it.