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

Access Modifiers on Fields

Learn best practices for field access: typically private fields with public or protected accessors.

Access Modifiers on Fields

What you'll learn: How to apply access modifiers to class fields and why making fields private with public accessors is the gold standard in Java.

The Core Principle

When you declare fields in a class, you choose who can directly read or modify them by applying an access modifier. The established best practice is simple: make fields private and control access through methods (getters/setters) when needed.

Why Private Fields?

Think of your object like a car. You don't want anyone reaching directly into the engine and yanking out parts. Instead, you provide a steering wheel, pedals, and a dashboard—controlled interfaces for interaction. Private fields protect your object's internal state the same way.

public class BankAccount {
    private double balance;  // Private: hidden from outside code
    private String owner;    // Private: protected internal data
    
    public double getBalance() {
        return balance;  // Public method: controlled access
    }
    
    public void deposit(double amount) {
        if (amount > 0) {  // Can validate before modifying!
            balance += amount;
        }
    }
}

The Four Choices for Fields

  • private: Only accessible within the same class (use this almost always)
  • Package-private (no modifier): Accessible within the same package (rarely for fields)
  • protected: Accessible to subclasses and same package (occasionally useful)
  • public: Accessible everywhere (avoid for fields—breaks encapsulation)

Why Not Public Fields?

Public fields expose your implementation. If you later need to validate data, log changes, or change how the field is stored, you'd have to modify every piece of code that touches it. With private fields and public methods, you control the interface.

Key Takeaway: Make fields private by default. Use public or protected accessor methods when you need controlled external access—this is fundamental to encapsulation and maintainable code.