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

Variables in classes as private or public

In java , Should I declare all my variable in my classes as private or public ?

It depends, however it's usually good practice to make them private. I'm not all that smart in java though so maybe someone else will have a better answer.

1 Answer

The common convention is to declare them as private, and then add getter/setter methods based on how you want them to be accessed. It is an example of Encapsulation which is often considered a fundamental part of object oriented programming.

By making your fields private and using getter/setter method to make them available outside the class you get a lot more control over what happens when they are accessed and how they are changed. Which allows you to make assumptions about the state of the field variables in your own code that would be unsafe to make if those variables could be changed from external code whenever and to whatever the external code wanted.