Course contentsShow
← Java
Lesson 336 of 2,8708. Classes and EncapsulationFree lesson

Common Access Modifier Mistakes

Identify frequent errors like making everything public or using protected when private would suffice.

Common Access Modifier Mistakes

What you'll learn: You'll discover the most frequent errors beginners make when choosing access modifiers and how to avoid them.

Now that you understand Java's four access levels, let's look at where developers often go wrong. These mistakes usually stem from not thinking carefully about encapsulation or from trying to avoid errors by making things "just work."

Mistake #1: Making Everything Public

The most common error is declaring all fields and methods public because it's convenient. This completely breaks encapsulation—every part of your program can reach in and modify your object's state.

public class BankAccount {
    public double balance;  // ❌ Anyone can set this!
    
    public BankAccount(double initial) {
        balance = initial;
    }
}

// Now anyone can do this:
BankAccount account = new BankAccount(100.0);
account.balance = -5000;  // Disaster!

Fix: Make fields private and provide controlled access through methods.

Mistake #2: Using Protected When Private Would Work

Another error is making fields protected "just in case" a subclass might need them later. If you're not actively using inheritance, this exposes your internals unnecessarily to the entire package.

public class User {
    protected String password;  // ❌ Overkill for now
}

Fix: Start with private. You can always widen access later if inheritance demands it.

Mistake #3: Forgetting Package-Private Consequences

Leaving off modifiers means package-private access—sometimes unintentionally. This lets any class in the same package access your members, which might be more than you intended.

Key Takeaway: Default to private for fields, use public only for methods that form your class's public interface, and choose protected or package-private only when you have a specific reason. When in doubt, start restrictive—you can always loosen access later, but tightening it breaks existing code.