
Java is an object-oriented programming language that uses access modifiers to control the visibility and accessibility of class members such as fields, methods, and constructors. Access modifiers specify the level of access that classes, methods, and variables have and help ensure data encapsulation and security.
Access Modifiers -
Java access modifiers are used to control the visibility or accessibility of classes, variables, methods, and constructors in Java. There are four access modifiers in Java: public, private, protected, and default (also known as package-private).
Public Access Modifier: The public access modifier is the most permissive modifier in Java. A class, method, constructor or variable declared as public can be accessed from anywhere in the program. Here's an example of a public class:
public class MyClass {
public int x;
public void myMethod() {
System.out.println("This is a public method");
}
}
Private Access Modifier: The private access modifier is the most restrictive modifier in Java. A class, method, constructor or variable declared as private can only be accessed within the same class. Here's an example of a private class:
public class MyClass {
private int x;
private void myMethod() {
System.out.println("This is a private method");
}
}
Protected Access Modifier: The protected access modifier allows access to a class, method, constructor or variable within the same package or through inheritance in a subclass. Here's an example of a protected class:
public class MyClass {
protected int x;
protected void myMethod() {
System.out.println("This is a protected method");
}
}
Default or Package-private Access Modifier: The default access modifier is the absence of an access modifier. A class, method, constructor or variable with no access modifier can only be accessed within the same package. Here's an example of a default class:
class MyClass {
int x;
void myMethod() {
System.out.println("This is a default method");
}
}
In summary, the access modifiers in Java allow you to control the visibility and accessibility of your code. By using access modifiers, you can hide implementation details and provide an interface for other code to use.
Modifiers summarized in one fig.

ImgRef - programiz
Thanks for reading, and happy coding!
Java Access Modifiers: Understanding Public, Private, Protected and Default -> Important keywords in Java