Access Modifiers in Java
Access modifiers control which other code is allowed to see or use a class, field, method, or constructor. Java has four levels: public (visible everywhere), protected (visible within the same package, plus subclasses in other packages), package-private — the default when no modifier is written at all (visible only within the same package) — and private (visible only within the declaring class itself).
The general convention is to keep fields private and expose controlled access through public methods, getters and setters, instead of letting outside code reach in and modify a field directly. That indirection is what makes it possible to validate a new value, or change the internal representation later, without breaking any code that already depends on the class.
public
Visible and usable from anywhere, any class, any package.
protected
Visible within the same package, and additionally to subclasses even in a different package.
package-private (the default)
Writing no modifier at all means visible only within the same package, nowhere else.
private
Visible only inside the declaring class itself, not even to subclasses.
The getter/setter convention
Keeping fields private and exposing controlled public methods to read or change them allows validation and internal changes without breaking outside code.
public class Account { private double balance; public Account(double balance) { this.balance = balance; } public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public static void main(String[] args) { Account acc = new Account(100); acc.deposit(50); System.out.println("Balance: " + acc.getBalance()); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.