Packages and Interfaces  «Prev 

Controlling access using Modifiers in Java

If you lack experience with object-oriented programming, you may not immediately see the significance of access modifiers.
The significance of access modifiers has to do with one of the main premises behind OOP, which is the encapsulation of data and behavior within a single construct, a class. It is very important for a class to manage its data internally and restrict access to other classes.
In other words, an outside class must call methods on a class to alter the class's state, as opposed to simply modifying the class's member variables directly. Access modifiers make this possible because they allow you to restrict the access to member variables.
They also go a step further and allow you to restrict the access to methods. This restriction is useful in situations where you may have a helper method that is only used within the inner workings of a class. In this case, you would not want other classes to be able to call the method. Java classes enter the access equation in a sense that you can restrict the access to an entire class. This is useful in situations where you may have a helper class that is only used by classes in a certain package.

Member Access

Access modifiers specify which methods can access which members. There are four access modifiers used in java. They are
  1. public,
  2. private,
  3. protected,
  4. no modifer (declaring without an access modifer).
Using no modifier is also sometimes referred as package-private or default or friendly access. Usage of these access modifiers is restricted to two levels. The two levels are class level access
  1. modifiers and
  2. member level access modifiers.