❔ What Are Access Modifiers?
Access modifiers in Java control the visibility (access level) of classes, methods, and variables.
They help with security, encapsulation, and code organization.
🔐 Types of Access Modifiers
Modifier | Accessible Within Class | Within Package | Subclass in Other Package | Other Packages |
|---|---|---|---|---|
| ✅ Yes | ❌ No | ❌ No | ❌ No |
(default) | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
| ✅ Yes | ✅ Yes | ✅ Yes | ❌ No |
| ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
🧠 If no modifier is specified, it's default/package-private.
🔐 private
Accessible only within the same class.
Best for data hiding and encapsulation.
class BankAccount {
private int balance = 1000;
public int getBalance() {
return balance;
}
}❌ Can't be accessed from another class directly.
🔓 public
Accessible from anywhere — any class, any package.
public class Main {
public static void main(String[] args) {
System.out.println("This is public.");
}
}✅ Use it when you want methods/classes to be available everywhere.
📦 default (No modifier)
Accessible only within the same package.
class Message {
void show() {
System.out.println("Default access");
}
}❌ Not visible outside the package.
🛡️ protected
Accessible within the same package and in subclasses (even in different packages).
class Animal {
protected void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
sound(); // allowed due to protected
}
}✅ Used mainly when doing inheritance + controlled access.
Practical Example
class Demo {
public int x = 1;
private int y = 2;
protected int z = 3;
int w = 4; // default
public void printValues() {
System.out.println(x + ", " + y + ", " + z + ", " + w);
}
}✅ All members are accessible within the same class
Outside class? Only x (public) and z (protected, if extended) may be accessible depending on the context.
👇 Outside Class Example: TestAccess.java
public class TestAccess {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println(d.x); // ✅ public — accessible
// System.out.println(d.y); // ❌ private — not accessible
System.out.println(d.z); // ✅ protected — accessible (same package)
System.out.println(d.w); // ✅ default — accessible (same package)
}
}1
3
4✅ Recap Table
Modifier | Scope | Use Case |
|---|---|---|
| Same class only | Hiding sensitive data |
| Same package only | Internal logic within a package |
| Same package + subclasses in other pkgs | Controlled inheritance access |
| Everywhere | General utility, entry points |