☰ See All Chapters |
Access and Non Access Modifiers in Java
Access specifiers specify who can access them. There are two types of modifiers in java: access modifier and non-access modifier.
Non Access Modifiers
Java provides a number of non-access modifiers to achieve much other functionality.
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
Access Modifiers
An access modifier specifies who can access them. There are four access modifiers used in java. They are public, private, protected, default (no keyword is used). Default access is also sometimes referred as ‘package-private’ or ‘friendly’ access.
Access modifiers cannot be used for local variables.
Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.
Class level access modifiers (java classes only)
Only two access modifiers is allowed, public and default
If a class is ‘public’, then it CAN be accessed from ANYWHERE.
If a class has no modifier ( default) then it CAN ONLY be accessed from ‘same package’
In the below example you can see class B is having default no modifier. This class is not accessible from outside the package in class HelloWorld. But class B is accessible within same package from class C. Class A is having public access specifier which is accessible from anywhere.
Member level access modifiers
Member level access modifiers apply to methods, constructors, fields.
Private and protected can be declared together. This gives visibility level in between private and protected.
Always declare constructors as public. (Try to declare).
Access modifier | public | protected | default | private protected | private |
Access Location | |||||
Same class | Yes | Yes | Yes | Yes | Yes |
Subclass in same package | Yes | Yes | Yes | Yes | No |
Other class in same package | Yes | Yes | Yes | No | No |
Subclass in other package | Yes | Yes | No | Yes | No |
Other class in other package | Yes | No | No | No | No |
In the below example you can see how the different member level access specifiers act on usage.
A source code file in Java can contain exactly one public class, and the name of the file must match the name of the public class with a .java extension.
You can declare more than one class in a .java file, but at most only one class can be declared public. The name of the source code file must still match the name of the public class. If there are no public classes in the source code file, the name of the file is arbitrary.
All Chapters