Java provides four main access modifiers that define the visibility and accessibility of classes, methods, variables, and constructors. These are public
, protected
, default
(no keyword), and private
. Let’s discuss them in detail:
1. public Access Modifier:
-
Scope: Accessible from anywhere in the program (same class, same package, subclasses, and other packages).
-
Usage: Used for classes, methods, and variables to make them universally accessible.
Syntax:
public class MyClass {
public void display() {
System.out.println("Public Method");
}
}
Code language: PHP (php)
2. protected Access Modifier:
-
Scope: Accessible within the same package and by subclasses in different packages (through inheritance).
-
Usage: Used to provide access to subclasses while restricting access to non-subclasses in different packages.
Syntax:
class Parent {
protected void show() {
System.out.println("Protected Method");
}
}
Code language: JavaScript (javascript)
3. default (Package-Private) Access Modifier:
-
Scope: Accessible only within the same package. It is the default modifier when no explicit access modifier is specified.
-
Usage: Used for restricting access to package-level visibility.
Syntax:
class PackageClass {
void display() {
System.out.println("Default Access");
}
}
Code language: JavaScript (javascript)
4. private Access Modifier:
-
Scope: Accessible only within the same class. Not visible to other classes, even in the same package.
-
Usage: Used to achieve encapsulation and prevent external modification of critical data.
Syntax:
class BankAccount {
private double balance;
private void calculateInterest() {
System.out.println("Private Method");
}
}
Code language: PHP (php)
Modifier | Class | Package | Subclass (Same Package) | Subclass (Different Package) | Other Packages |
---|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ | ✅ (through inheritance) | ❌ |
default |
✅ | ✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ | ❌ |
-
public
provides the highest level of access, allowing visibility everywhere. -
protected
grants access to the same package and subclasses (even in different packages). -
default
restricts access to within the same package only. -
private
is the most restrictive, confining access to within the class itself.
Choosing the right access modifier ensures proper encapsulation, modularity, and security in Java applications.