Java has four access levels. Three come from keywords, public, protected and private, and the fourth comes from writing no keyword at all. That fourth level is called package-private, and it is the default. Package-private members are visible to code in the same package and to nothing outside it.
The four levels
publicmembers are visible everywhere the class itself is visible.protectedmembers are visible in the same package, and in subclasses, including subclasses in other packages.- Package-private members, with no keyword, are visible only within the same package.
privatemembers are visible only inside the class that declares them.
Who can reach what
| Level | Same class | Same package | Subclass in another package | Any other code |
|---|---|---|---|---|
private |
Yes | No | No | No |
| Package-private | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
A subclass in another package can reach a protected member only through an object of the subclass’s own type, not through a reference to the base type.
An example in a package
package shop;
public class Product {
public String name; // visible everywhere
protected double cost; // shop package and subclasses
String category; // shop package only, no keyword
private String supplierCode; // this class only
}
Top-level classes
A top-level class can be public or package-private. It cannot be private or protected. Those two levels only make sense for classes nested inside another class.
How this differs from C++
C++ has no packages, so C++ protected has no package-level part. It covers only the class, its friends and derived classes. C++ class members are private by default, while Java members with no keyword are package-private. Access Modifiers in C++ covers the C++ rules in full, and Encapsulation in C++ explains the idea behind private fields with getters and setters, which both languages use.