Java Java Data Structures Efficiency! Design the UI

Grigorij Schleifer
Grigorij Schleifer
10,350 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,350 Points

Hi Enrique,

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