🔑 What are Access Modifiers?
- Access modifiers define the visibility or accessibility of classes, methods, and variables.
- They control who can access what in your program.
- Java has four main access modifiers:
Modifier | Class | Package | Subclass | World (anywhere) |
---|---|---|---|---|
private | ✔ | ✖ | ✖ | ✖ |
default | ✔ | ✔ | ✖ | ✖ |
protected | ✔ | ✔ | ✔ | ✖ |
public | ✔ | ✔ | ✔ | ✔ |
“Default” access is when no modifier is specified.
🔑 1. Private
- Accessible only within the same class.
- Used to encapsulate data.
class Test {
private int secret = 42;
void showSecret() {
System.out.println(secret);
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
t.showSecret(); // OK
// System.out.println(t.secret); // ❌ Compile error
}
}
🔑 2. Default (Package-Private)
- Accessible within the same package.
- No keyword is used.
class Test {
int number = 10; // default access
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.number); // OK if same package
}
}
🔑 3. Protected
- Accessible within the same package and subclasses (even in different packages).
package pkg1;
class Parent {
protected int data = 50;
}
package pkg2;
import pkg1.Parent;
class Child extends Parent {
void show() {
System.out.println(data); // OK: protected accessed in subclass
}
}
🔑 4. Public
- Accessible from anywhere (any class, any package).
public class Test {
public int number = 100;
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.number); // Accessible anywhere
}
}
🔑 Quick Rules:
- Class Level → Can only be
public
or default. - Members (fields & methods) → Can be
private
, default,protected
, orpublic
. - Encapsulation tip → Make fields
private
and methodspublic
(getter/setter).
✅ Summary Table
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
private | ✔ | ✖ | ✖ | ✖ |
default | ✔ | ✔ | ✖ | ✖ |
protected | ✔ | ✔ | ✔ | ✖ |
public | ✔ | ✔ | ✔ | ✔ |