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
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,639 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.