In Java, access modifiers are keywords used to define the visibility or accessibility of classes, methods, constructors, and fields within different parts of a program. There are four access modifiers in Java:
-
public
- The member (class, method, or variable) is accessible from anywhere (other classes, packages, etc.).
- Example:
public class MyClass { public int myVar; public void myMethod() { System.out.println("Public method"); } }
-
private
- The member is accessible only within its own class.
- Example:
public class MyClass { private int secretVar; private void secretMethod() { System.out.println("Private method"); } }
-
protected
- The member is accessible within its own class, subclasses (even in different packages), and other classes in the same package.
- Example:
public class Parent { protected int familyVar; protected void familyMethod() { System.out.println("Protected method"); } }
-
default
(no modifier - package-private)- The member is accessible only within the same package (no keyword is used).
- Example:
class MyPackageClass { int packageVar; // default access void packageMethod() { System.out.println("Default access method"); } }
Summary Table:
Modifier | Class | Package | Subclass (Same Pkg) | Subclass (Diff Pkg) | World (Anywhere) |
---|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ | ✅ | ❌ |
default |
✅ | ✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ | ❌ |
Key Points:
-
Classes can be
public
ordefault
(no modifier). They cannot beprivate
orprotected
(unless nested inside another class). - Constructors, methods, and variables can use all four access modifiers.
Example:
package com.example;
public class AccessExample {
public int publicVar = 1;
protected int protectedVar = 2;
int defaultVar = 3; // package-private
private int privateVar = 4;
public void display() {
System.out.println(privateVar); // privateVar is accessible here
}
}
Understanding access modifiers helps in encapsulation (data hiding) and controlling how classes interact in Java.