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 Java Objects (Retired) Delivering the MVP Refactoring

Ayman Syam
Ayman Syam
2,346 Points

Who can use the public and private classes/methods?

This question goes a little back, but to whom exactly do public and private refer to? Do they refer to users or to other programmers who are building upon the code? Thanks.

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Ayman,

"private" and "public" are access modifiers for you and other programmers.

  • Public variables, are variables that are visible to all classes and everyone can use them.
  • Private variables, are variables that are visible only to the class to which they belong

So if you want to protect your code you can encapsulate it. Set the variable as private and use a public getter method. Other programmers canΒ΄t change the private field, they have to use the getter method to access the private variable.

Makes sense?

Grigorij