Various Access Modifiers in Java
Java provides four access modifiers to set
access levels for classes, variables, methods and constructors. The four access
to the world (public).
to the package and all subclasses only (protected).
to the class only (private).
to the package. No modifiers are needed.
Public Access Modifier:
If any class, method,
constructor, etc. is declared “public”, then it can be accessed from any other
class. Therefore methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe. But then to, if the public class
we are trying to access is in some other package, then the public class still
need to be imported. Because of class inheritance, all public methods and
variables of a class can be inherited by its subclasses.
Protected Access Modifier:
If we declare variables,
methods and constructors as “protected” in a superclass, then it can be
accessed only by the subclasses in other package or any class within the
package of the protected members’ class.
It cannot be applied to
class and interfaces. Methods, fields can be declared protected, however
methods and fields in an interface cannot be declared protected.
Private Access Modifier:
we declare any methods, variables and constructors private, then they can only
be accessed within the declared class. It is the most restrictive access level.
Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public
getter methods are present in the class.
the variables and methods as “private” is the best way to encapsulate object
and hide its data from the outside world.
If we do not declare any
access modifier for a class, variable, method, etc., then it is consider it to
be default access modifier. A variable or method declared without any access
modifier is available to any other class in the same package.