Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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