Access modifiers are keywords in Java that control who can access a class, variable, method, or constructor.
Java has four access levels:
publicprivateprotecteddefaultThe main purpose is to control visibility and access.
For example:
class Student {
public String name;
private int age;
}
Here, name can be accessed from outside the class, but age cannot be accessed directly from outside because it is private.
publicpublic means the member is accessible from anywhere, provided the containing class itself is accessible.
class Student {
public String name;
public void display() {
System.out.println(name);
}
}
From another class:
Student s = new Student();
s.name = "Rahul";
s.display();
Both are accessible because they are public.
public dataType variable;
public returnType method() {
}