Access Modifiers

What Are Access Modifiers in Java?

Java has four access levels: public, protected, private and package-private, the default with no keyword. Examples and a comparison with C++.

On this page
  1. The four levels
  2. Who can reach what
  3. An example in a package
  4. Top-level classes
  5. How this differs from C++

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

  • public members are visible everywhere the class itself is visible.
  • protected members 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.
  • private members 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.

The complete guide to access modifiers

Access Modifiers in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

The Latest C++ Standard

C++23 is the most recent C++ standard at the time of writing, with C++26 next. Here is what changed, how versions are named, and how to compile for each.

C++ Standards 3 min read