The Four Access Levels in Java
What you'll learn: How to control which parts of your code can see and use your class members using Java's four access modifiers.
Why Access Levels Matter
When building classes, you need to decide who can access your fields and methods. Should they be visible everywhere, only within the same class, or somewhere in between? Java gives you four access levels to control this visibility.
The Four Access Modifiers
1. private — Most Restrictive
Only code within the same class can access the member. Other classes cannot see it at all.
class BankAccount {
private double balance; // Only BankAccount methods can touch this
}
2. package-private (default) — No Keyword When you don't write any modifier, the member is visible to all classes in the same package. This is the "default" access level.
class Helper {
int sharedValue; // Visible to all classes in this package
}
3. protected
Visible within the same package and to subclasses (even if they're in different packages).
class Parent {
protected void helperMethod() { } // Subclasses can call this
}
4. public — Least Restrictive
Visible everywhere. Any class in any package can access it.
public class Calculator {
public int add(int a, int b) { // Anyone can call this
return a + b;
}
}
Analogy: Doors in a Building
- private: Your personal diary—only you can read it
- package-private: Department files—everyone in your department can access
- protected: Family heirlooms—your family and descendants can use them
- public: The lobby—open to everyone
Key Takeaway: Java's four access levels—private, package-private (default), protected, and public—control who can see and use your class members, with private being most restrictive and public being most open.