Access Modifiers in Java
Access modifiers in Java determine where a class, field, method, or constructor can be used from. Java has four levels of access: public, protected, defaul...
Controlling Visibility with Access Modifiers
Access modifiers in Java determine where a class, field, method, or constructor can be used from. Java has four levels of access: public, protected, default (package-private, written with no keyword), and private. These modifiers are a core tool for encapsulation—hiding implementation details and exposing only what external code needs to use.
The Four Levels Explained Private members are visible only within the class that declares them. Default (no modifier) members are visible within the same package. Protected members are visible within the same package and also to any subclass, even in a different package. Public members are visible everywhere—any class in any package that can see the class can use the member. The access levels form a hierarchy of increasing visibility: private < default < protected < public.
Applying Modifiers to Classes and Members Top-level classes can only be public or package-private (default). Inner classes can use all four modifiers. Fields should almost always be private, with access granted through getter and setter methods. Constructors are usually public but can be private (Singleton), protected (for class hierarchies), or package-private (for factory patterns limited to a package). Methods that form the public API of a class are public; helper methods used only internally are private.
Why Access Control Matters in Large Systems In a small program, access control might seem like extra ceremony. In a large system with many developers, it becomes essential. When a field is public, any class anywhere can change it directly, making it impossible to guarantee the object's state is valid. When the field is private and access goes through a setter, you can add validation logic in one place: if (age < 0) throw new IllegalArgumentException(). This prevents invalid state from propagating throughout the system.
Code Example: class BankAccount { private double balance;
public void deposit(double amount) { if (amount > 0) balance += amount; }
public double getBalance() { return balance; } }
BankAccount acct = new BankAccount(); acct.deposit(500); // acct.balance = -100; // compile error - private
Interview Tip: A common trick question asks whether protected members of a parent class are accessible in a child class that lives in a different package. They are, but only through inheritance—the child class can access protected members on itself (this) or other instances of the same child type, but not on raw instances of the parent class. This nuance is specifically covered in the Java Language Specification and appears in OCPJP exam questions.