private Members: Encapsulation Within the Class
What you'll learn: How the private access modifier locks members strictly within the declaring class, forming the foundation of encapsulation.
The Core Idea
The private access modifier is the most restrictive visibility level in Java. When you mark a field or method as private, it becomes accessible only within the body of that same class—nowhere else. Not in subclasses, not in other classes in the same package, not anywhere outside the class boundaries.
This restriction is the cornerstone of encapsulation: hiding internal implementation details and controlling how the outside world interacts with your class.
How private Works
Think of a private member like a secret diary entry. Only you (the class itself) can read or modify it. Even your closest friends (classes in the same package) or your children (subclasses) cannot access it directly.
public class BankAccount {
private double balance; // Only BankAccount methods can touch this
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Private field accessed within its own class
}
}
public double getBalance() {
return balance; // Controlled access through a public method
}
}
In another class, even in the same package:
public class Transaction {
public void processPayment() {
BankAccount account = new BankAccount();
// account.balance = 1000000; // COMPILE ERROR! balance is private
account.deposit(100); // OK - using the public interface
}
}
Why This Matters
By making fields private, you force all access through public methods, giving you complete control over validation, business rules, and internal changes without breaking external code.
Key Takeaway:
private members are visible only within their declaring class, creating a protective boundary that enforces true encapsulation and hides implementation details from all other code.