Access Modifiers
Java gives you four levels of visibility for classes, fields, methods, and constructors: public, protected, private, and package-private — the level you get when you write no modifier at all. Each one controls exactly which other code is allowed to see and use a given member.
Who can access what
Modifier | Same class | Same package | Subclass (different package) | Everywhere |
|---|---|---|---|---|
| Yes | Yes | Yes | Yes |
| Yes | Yes | Yes | No |
(package-private, no keyword) | Yes | Yes | No | No |
| Yes | No | No | No |
public
Accessible from any code, anywhere, regardless of package. Used for the parts of a class that make up its public API — the methods and constructors other code is meant to call.
protected
Accessible within the same package, plus from subclasses even if they live in a different package. It's designed specifically for members that subclasses need to inherit and use, but that shouldn't be part of the general public API.
private
Accessible only from inside the same class. Not visible to subclasses, not visible to other classes in the same package — nowhere else at all. This is the modifier that makes encapsulation possible: a private field can only ever be touched through the class's own methods.
Package-private (default)
If you omit a modifier entirely, the member is accessible from anywhere in the same package, but invisible outside it. It's a useful middle ground for helper classes and methods that several classes in one package need to share, without exposing them to the rest of the application.
All four modifiers on one class
package com.example.billing;
public class Invoice {
public String invoiceNumber; // visible everywhere
protected double subtotal; // visible to subclasses + same package
double taxRate; // package-private: same package only
private double discount; // visible only inside Invoice itself
private double applyDiscount(double amount) {
return amount - (amount * discount);
}
public double total() {
// total() can freely use the private helper and private field
return applyDiscount(subtotal + (subtotal * taxRate));
}
}Applying modifiers to classes, fields, methods, constructors
Top-level classes can only be
publicor package-private — notprotectedorprivate.Fields, methods, and constructors can use any of the four levels.
Nested classes (see the Nested & Inner Classes page) can additionally be
privateorprotected, since they behave like members of the enclosing class.