The <code>private</code> Access Modifier in Java

private is the most restrictive access modifier in Java. A private member is visible only inside the declaring class β€” not subclasses, not the same package, not reflection (without setAccessible(true)).

Where to use it

  • Default for fields β€” encapsulation means hiding state behind methods.
  • Helper methods inside a class β€” implementation detail, not part of the public API.
  • Constructors of utility classes and singletons (prevent instantiation).
  • Nested classes used only by the outer class.

Example

public class BankAccount {
    private final String owner;
    private BigDecimal balance;

    public BankAccount(String owner) { this.owner = owner; balance = BigDecimal.ZERO; }
    public void deposit(BigDecimal amount) {
        validate(amount);
        balance = balance.add(amount);
    }

    private void validate(BigDecimal amount) {      // internal helper
        if (amount.signum() <= 0) throw new IllegalArgumentException();
    }
}

Private in interfaces (Java 9+)

public interface Logger {
    default void info(String m)  { log("INFO",  m); }
    default void error(String m) { log("ERROR", m); }
    private void log(String level, String m) {      // shared helper, hidden from implementers
        System.out.println("[" + level + "] " + m);
    }
}

What it doesn't protect against

  • Reflection β€” field.setAccessible(true) bypasses it. Java modules can block this.
  • Serialisation β€” fields are written/read as raw bytes unless marked transient.
  • Lombok and friends β€” annotation processors can synthesise public accessors. That's intentional.

Top-level classes can't be private

Only nested and inner classes can. For a top-level class, use package-private (no keyword).

Common mistakes

  • Public fields β€” bypasses encapsulation entirely.
  • Package-private by default β€” if only the declaring class needs access, use private.
  • Protected fields as a default β€” breaks encapsulation for subclasses. Expose via protected methods, keep fields private.

Related

Pillar: Java access modifiers. See also public, encapsulation.