Access and Non Access Modifiers in Java, Java public modifier, Java private modifier, Java default modifier, and Java static modifier.
Modifiers in Java
Java provides a rich set of modifiers. They are used to control access mechanisms and also provide information about class functionalities to JVM.
Java has two categories of modifiers:
1. Access Modifiers :
Access Modifiers can be used to define access control for classes, methods, and variables. Java has four access modifiers, public, private, protected, and default.
Note: If you don’t specify any modifier then it is treated as ‘default’ modifier.
i. public
public access modifier is accessible everywhere.
Example:
public class Sample{
…..
}
public int a =10;
public int add (Parameters){
method body…
}
ii. private
The private access modifier is accessible only within the class
private int b=200;
iii. default
if we don’t specify any modifier then It is treated as default, this can be accessed only within the package
Example:
class Sample{
…..
}
iv protected
The protected modifier is accessible within the package, outside of the package but through Inheritance.
Example:
protected class Sample{
….
}
Modifier | Within the Class | Within the Package | Outside of the Package by a Subclass | Outside of the Package |
private | Y | N | N | N |
default | Y | Y | N | N |
protected | Y | Y | Y | N |
public | Y | Y | Y | Y |
2. Non-access modifiers:
In java, we have seven non-access modifiers. They are used with classes, methods, variables, constructors, etc to provide information about their behavior to JVM. They are:
i. static
ii. final
iii. abstract
vi. synchronized
v. transient
vi. volatile
vii. native
i. static
the static modifier is used to create classes, methods, and variables.
Example:
static int a=10;
static int add (parameters){
…………..
…………..
}
ii. final
final modifier for finalizing classes, methods, and variables.
Example:
final int x =100;//Correct
final int y;//Incorrect
y=200;
iii. abstract
the abstract modifier is used to create abstract classes and abstract methods.
Example:
abstract class Sample{
……..
}
abstract int add(); //abstract method
public int add(){ //concreate method
………..
}