×
☰ 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.

  1. The static modifier for creating class methods and variables 

  2. The final modifier for finalizing the implementations of classes, methods, and variables. 

  3. The abstract modifier for creating abstract classes and methods. 

  4. The synchronized and volatile modifiers, which are used for threads. 

Access Modifiers

  1. 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.   

  2. Access modifiers cannot be used for local variables. 

  3. 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

  1. If a class is ‘public’, then it CAN be accessed from ANYWHERE. 

  2. 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.

java-access-specifiers-0
 

Member level access modifiers

  1. Member level access modifiers apply to methods, constructors, fields. 

  2. Private and protected can be declared together. This gives visibility level in between private and protected. 

  3. Always declare constructors as public. (Try to declare). 

java-access-specifiers-1
 

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.

 

java-access-specifiers-2
 

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
Author