Java Access Modifiers
Java access modifiers control the visibility of classes, methods, variables, and constructors. They help protect data by deciding which parts of a program can access a particular member. Using the correct access modifier improves security, encapsulation, and code organization.
Java provides four types of access modifiers: public, private, protected, and default (no modifier).
What are Access Modifiers in Java?
Access modifiers define the scope or accessibility of Java classes and their members. They determine whether a class, method, or variable can be accessed from the same class, package, subclass, or other packages.
Types of Java Access Modifiers
- Public
- Private
- Protected
- Default (No Access Modifier)
Public Access Modifier
The public access modifier provides the highest level of accessibility. Public classes, methods, and variables can be accessed from anywhere in the project, including different packages.
public class Student{
public void display(){
System.out.println("Public Method");
}
}
Private Access Modifier
The private access modifier allows members to be accessed only within the same class. It is mainly used for data hiding and is a key part of encapsulation.
public class Student{
private int age = 20;
}
The variable age cannot be accessed directly from another class.
Usually, getter and setter methods are used to access private variables.
Protected Access Modifier
The protected access modifier allows access within the same package and also from subclasses located in different packages through inheritance.
protected void show(){
System.out.println("Protected Method");
}
Default Access Modifier
When no access modifier is specified, Java uses the default access modifier. Members with default access are available only within the same package.
class Student{
void display() {
System.out.println("Default Access");
}
}
Java Access Modifier Comparison
| Modifier | Same Class | Same Package | Subclass | Other Package |
|---|---|---|---|---|
| Public | ✔ | ✔ | ✔ | ✔ |
| Protected | ✔ | ✔ | ✔ | Inheritance Only |
| Default | ✔ | ✔ | ✘ | ✘ |
| Private | ✔ | ✘ | ✘ | ✘ |
Why Use Access Modifiers?
Security
Prevents unauthorized access to important data.
Encapsulation
Helps hide implementation details from users.
Maintainability
Makes Java applications easier to maintain and modify.
Code Safety
Prevents accidental modification of important members.
Summary
Java access modifiers define how classes, methods, and variables can be accessed. The public modifier provides access everywhere, private restricts access to the same class, protected allows access within the package and subclasses, while the default modifier limits access to the same package. Choosing the appropriate access modifier improves security, code quality, and supports the principles of object-oriented programming.