The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are two types of modifiers in Java:
1. Access modifiers
2. Non-access modifiers
As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java:
If we don’t specify any access modifier then it is treated as default modifier. It is used to set accessibility within the package. It means we can not access its method or class fro outside the package. It is also known as package accessibility modifier.
//save by Simple.java
package package1;
public class Simple {
int a = 20;
// default access modifier
void display() {
System.out.println(a);
}
}
//save by Test.java
import package1.Simple;
public class Test {
public static void main(String[] args) {
Simple obj = new Simple();
obj.display(); // compile error
}
}
Output:
The method display() from the type Simple is not visible
The methods or data members declared as private are accessible only within the class in which they are declared.
Any other class of the same package will not be able to access these members.
//save by Simple.java
class Simple {
int a = 20;
// private access modifier
private void display() {
System.out.println(a);
}
}
//save by Test.java
public class Test {
public static void main(String[] args) {
Simple obj = new Simple();
obj.display(); // compile error
}
}
Output:
The method display() from the type Simple is not visible
There isn’t any restriction on the classes, methods, and data members defined by the Public Access Modifiers. They can be accessed from anywhere. The keyword ‘public’ is used to define the Public Access Modifier.
//save by Simple.java
package package1;
public class Simple {
int a = 20;
// public access modifier
public void display() {
System.out.println(a);
}
}
//save by Test.java
package package2;
import package1.Simple;
public class Test {
public static void main(String[] args) {
Simple obj = new Simple();
obj.display();
}
}
Output:
20
The methods or data members declared as protected are accessible within the same package or subclasses in different packages.
//save by Simple.java
package package1;
public class Simple {
int a = 20;
// public access modifier
public void display() {
System.out.println(a);
}
}
//save by Test.java
package package2;
import package1.Simple;
public class Test {
public static void main(String[] args) {
Test obj = new Test();
obj.display();
}
}
Output:
20