logo
Access specifiers in java
Access specifiers in java
An access specifier is a keyword that is used to specify how to access a member of a class or the class itself. It means, we can use access specifiers with the members of a class or with the class also. There are 4 access specifiers in java.
1) public
2) private 
3) protected
4) default
Java Images
Public:-
This is the modifier applicable for classes, methods and variables (only for instance and static variables but not for local variables).
If a class is declared with public modifier then we can access that class from anywhere (within the package and outside of the package).
If we declare a member(variable) as a public then we can access that member from anywhere but Corresponding class should be visible i.e., before checking member visibility we have to check class visibility.
Default:-
This is the modifier applicable for classes, methods and variables (only for instance and static variables but not for local variables).
If a class is declared with modifier then we can access that class only within that current package but not from outside of the package.
Default access also known as a package level access.
The default modifier in the java language is default.
Private:-
private is a modifier applicable for methods and variables.
If a member declared as private then we can access that member only from within the current class.
If a method declare as a private we can access that method only within the class. it is not possible to call even in the child classes also.
Protected :-
If a member declared as protected then we can access that member with in the current package anywhere but outside package only in child classes.
But from outside package we can access protected members only by using child reference. If we try to use parent reference we will get compile time error.
Members can be accesses only from instance area directly i.e., from static area we can't access instance members directly otherwise we will get compile time error.