Access specifiers in Java are keywords. They are used to achieve encapsulation, which involves selectively hiding or exposing the properties of a programming language within a class.
Types of Access Specifiers in Java
Java has three access specifiers: public, protected, and private. However, if there are no modifiers or access specifiers in a program, JVM assigns a default modifier to the variables. Consequently, there are four access specifiers in Java. The list includes,
- public
- protected
- private
- default
Do not prefix the access specifiers with capitals; instead, they should start only with small letters.
In Java, access specifiers help achieve encapsulation, which involves selective exposure or hiding.
Public Access Specifier
The programmer can expose all the properties inside the class by using the public keyword.
In Java, the public access specifiers are similar to public hospitals, where people from any social and economic background can seek admission without fulfilling any criteria. The other meaning of public is that everyone can generally access the properties. Likewise, by declaring a variable or method as public, it is accessible from different classes.
Consider there are two packages, pack one and pack two.
The package in Java generally contains classes, interfaces, and enums.
For instance, class A is in pack 1, and class B is in pack 2.
If the variables and methods in class ‘B’ are declared public, then class ‘A’ can also access those variables and methods from class ‘B.’
Thus, the program can access properties from any location through the public keyword. Like from any package (for example, pack 2), and even the class B of Pack 2.
Everyone can access it at any level or scope by using the public. The highest scope of visibility of a property inside the Java API is the package.
Private Access Specifier
Through private access specifier in Java, the programmer can access properties from within the class only.
Protected Access Specifier
Protected access specifiers allows accessing of properties from within the class and within package.
Default Access Specifiers
Lastly, default access specifiers allows access with some conditions.