Member-Level Access Modifiers: The Four Options
What you'll learn: You'll understand the four access levels available for fields, methods, and constructors, and how they control visibility across your codebase.
The Four Access Levels
Unlike top-level classes (which only have public and package-private), class members—fields, methods, and constructors—can use all four access modifiers:
private– Visible only within the same class- Package-private (default) – Visible within the same package (no modifier keyword)
protected– Visible within the same package AND to subclasses in other packagespublic– Visible everywhere
How They Work
Think of these as security clearance levels for your code:
privateis like a personal diary—only you (the class) can read it- Package-private is like sharing with your immediate team (same package)
protectedextends access to your "extended family" (subclasses)publicis broadcasting to the world
package com.example;
public class Account {
private String accountId; // Only Account can access
double balance; // Package-private: any class in com.example
protected String customerName; // Same package + subclasses elsewhere
public void deposit(double amount) { // Anyone, anywhere
balance += amount;
}
}
When to Use Each
private: Default choice for fields and helper methods—maximize encapsulation- Package-private: Implementation details shared within a module/package
protected: Designed for inheritance—letting subclasses access implementationpublic: Your class's official API that external code depends on
Key Takeaway: All four access modifiers work on fields, methods, and constructors, giving you fine-grained control over encapsulation—from completely hidden (private) to fully exposed (public).