Access level modifiers in Java

In the Java programming language we can assign different levels of accessibility to every member of a class (top-level class, variables, methods). This is an important part of the language because it allows us to declare access to objects and classes in a concise and restrictive way.

Java provides 4 accessibility levels:

  1. private: the more restrictive. A member declared as private can only be accessed within its own class.
  2. package-private (no explicit modifier): only the classes within the same package have access to members declared as package-private.
  3. protected: as with package-private and, in addition, subclasses of the class containing protected members are able to access this members.
  4. public: the less restrictive. A member declared as public is visible to all classes everywhere.

Let’s see the following examples to better understand accessibility levels:

We can combine and create more scenarios to explain accessibility levels, but rather it’s worth to highlight why this is important when we are developing software in Java. The idea of this is to follow the principles of information hiding and encapsulation in such a way that only the communication between modules occurs through their APIs. Those principles can help us to make good software design.

For more information about this I recommend the book Effective Java (2nd Edition) of Joshua Bloch, item 13.