The most used access modifiers are undoubtedly public
and private
.
public
means you expose your field or method to every other class. This is useful for methods that are necessary to let the class perform its major function(s) and, in some cases, for constants that need to be visible.
private
means you hide the member from every other class. This is useful for internal state and functions which other classes must not know about. This enforces the concept of information hiding
.
The other modifiers protected
and default (when no modifier is mentioned) are intermediate levels of access which can be useful in specific cases.
For example when sub classes need access to a method in the parent (or base) class and you don't want other classes to be able to access it, you can make it protected
.
The default access modifier is more restricting than protected
and can be used to allow access only from within the same package. This can be useful if a package contains a group of tightly related classes which need to interact among each other via methods which you don't want to expose elsewhere, not even to sub classes outside this package.
Maybe you will also benefit from this article.