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 Data Structures Efficiency! Design the UI

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Why instance variables must be signed as private???

Can someone explane me the difference between private and static ... or protected ... I am still totally unsure how to use this keywords properly ...

2 Answers

Enrique Munguía
Enrique Munguía
14,311 Points

There are four levels of access modifieres in Java: public, private, protected and default (there is no default keyword, just declare a variable without modifier). Regarding your question, the private modifier is used to prevent access of variables from the ouside (other classes), in order to conform to Encapsulation principle in Object Oriented Programming. This is a convention, and you should follow it, if you want to access to those variables from other classes you can mark them as public.

public class Example {
  public int var1; // this variable is accessible from any class
  protected int var2; // this cariable is accessible from classes of the same package, and any subclass
  int var3; // default modifier, this variable is accessible from classes of the same package
  private var4; // this variable is only accesible from this class
Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Enrique,

I don´t understand how to use this access modifieres ...