Access modifiers in Java are keywords used to set the accessibility or visibility of classes, variables, constructors, and methods.
Java provides four types of access modifiers: `Default`, `Public`, `Private` and `Protected`.
If no access modifier is specified, the default access level is package-private.
Members with package-private access are accessible within the same package but not from outside the package.
It is used when we want to restrict access to class members within the same package.
class YourClass { int age; // default Access Modifier variable void someMethod() { // default Access Modifier Method // Method code } }
Members declared as public are accessible from any other class. There are no restrictions on their accessibility.
// Public Class public class YourClass { public int age; // public Access Modifier variable public void someMethod() { // public Access Modifier method // Method Code } }
It is used for classes, methods, and variables that need to be accessible from anywhere in the program.
public class YourClass { private int age; // private Access Modifier Variable private void someMethod() { // private Access Modifier Method // Method code } }
Members declared as private are accessible only within the same class. They are not visible to any other class, even subclasses.
Private is used to encapsulate and protect the internal implementation details of a class.
class YourClass { protected int age; // protected Access Modifier Variable protected void someMethod() { // protected Access Modifier method // Method code } }
Members declared as protected are accessible within the same package and from subclasses, even if they are in different packages.
However, if a subclass is in a different package, the subclass can only access protected members using inheritance.
it used to provide access to class members to subclasses for inheritance purposes.
Modifier | World | Package | Class | Subclass |
---|---|---|---|---|
private | N | N | Y | N |
Default | N | Y | Y | N |
Protected | N | Y | Y | Y |
Public | Y | Y | Y | Y |
These access modifiers help in implementing encapsulation and access control in Java programs, ensuring proper visibility and encapsulation of classes and their members.
By using appropriate access modifiers, we can design classes and interfaces with controlled accessibility, which enhances the security, maintainability, and reusability of your code.