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 trialRana P
885 PointsPrivate 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
Front End Web Development Techdegree Graduate 84,738 Pointsprivate
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.