Access Modifiers in Java

Access modifiers decide which code may use a class, field, method or constructor. Java has four levels, and two of them, package-private and protected, behave in ways that surprise people. This page explains what each level is for, proves the rules by compiling a two-package project with javac, and then covers what access modifiers do not protect against: leaked mutable objects and reflection.

Contents

Why access modifiers exist

Access modifiers are the tool for encapsulation: deciding which parts of a class are its public contract and which are internal details that can change without breaking other code. If a field is private, the class can rename it, change its type or add validation, and no other code needs to change. If it is public, every user of the class may depend on it forever.

Java checks access at compile time (javac refuses the code) and again when classes are linked at run time. There are four levels, from most to least restrictive:

Who can access a member at each level
ModifierSame classSame packageSubclass in another packageAny other code
privateYesNoNoNo
(none): package-privateYesYesNoNo
protectedYesYesYes, through inheritanceNo
publicYesYesYesYes
  • Package-private is what you get by writing no modifier. There is no keyword for it (default means something else, in interfaces and switches).
  • protected is wider than package-private, not narrower: it includes the whole package, plus subclasses elsewhere.
  • A top-level class can only be public or package-private, and a file may contain at most one public top-level class, whose name must match the file name. Nested classes can use all four levels.
  • Local variables never take access modifiers; they are visible only inside their block anyway.

Proving the rules with javac

Rather than describing the rules, this program writes a small project with two packages to a temporary folder, compiles it with the JDK's own compiler, and prints every error javac reports. Each source file contains lines that should compile and lines that should not, marked with comments. The package bank owns an Account with one field at each access level; the package app uses it from outside, once as an ordinary user and once as a subclass.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

// Compiles two small packages with javac and prints which accesses it rejects
public class AccessCheck {

    static final String ACCOUNT = """
            package bank;

            public class Account {
                private long balance;            // only inside Account
                long branchCode;                 // package-private: anything in 'bank'
                protected String owner;          // 'bank' plus subclasses anywhere
                public String id;                // everyone

                public long getBalance() {
                    return balance;
                }
            }
            """;

    static final String TELLER = """
            package bank;

            class Teller {                       // package-private class
                void audit(Account a) {
                    long code = a.branchCode;    // OK: same package
                    String who = a.owner;        // OK: protected includes the package
                    long b = a.balance;          // error: private
                }
            }
            """;

    static final String APP = """
            package app;

            import bank.Account;

            public class App {
                void use(Account a) {
                    String id = a.id;            // OK: public
                    long bal = a.getBalance();   // OK: public method
                    long code = a.branchCode;    // error: package-private
                    String who = a.owner;        // error: protected, not a subclass
                }
            }
            """;

    static final String SAVINGS = """
            package app;

            import bank.Account;

            public class Savings extends Account {
                void label(Savings own, Account other) {
                    owner = "inherited";         // OK: protected, through inheritance
                    String mine = own.owner;     // OK: reference of the subclass type
                    String theirs = other.owner; // error: through a plain Account reference
                }
            }
            """;

    static final String NARROW = """
            package app;

            import bank.Account;

            public class Narrow extends Account {
                @Override
                long getBalance() {              // error: an override cannot be less visible
                    return 0;
                }
            }
            """;

    static final String HIDDEN = """
            package app;

            private class Hidden {               // error: top-level classes are public or
            }                                    // package-private only
            """;

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("access");
        write(root, "bank/Account.java", ACCOUNT);
        write(root, "bank/Teller.java", TELLER);
        write(root, "app/App.java", APP);
        write(root, "app/Savings.java", SAVINGS);
        write(root, "app/Narrow.java", NARROW);
        write(root, "app/Hidden.java", HIDDEN);

        List<String> files;
        try (Stream<Path> s = Files.walk(root)) {
            files = s.filter(p -> p.toString().endsWith(".java"))
                    .map(Path::toString).sorted().toList();
        }
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        ByteArrayOutputStream errors = new ByteArrayOutputStream();
        String[] options = Stream.concat(Stream.of("-d", root.resolve("out").toString()),
                files.stream()).toArray(String[]::new);
        javac.run(null, null, new PrintStream(errors, true, StandardCharsets.UTF_8), options);

        errors.toString(StandardCharsets.UTF_8).lines()
                .filter(l -> l.startsWith(root.toString()) || l.contains("weaker access"))
                .map(l -> l.startsWith(root.toString())
                        ? l.substring(root.toString().length() + 1) : "    " + l.strip())
                .forEach(System.out::println);
    }

    static void write(Path root, String rel, String code) throws IOException {
        Path file = root.resolve(rel);
        Files.createDirectories(file.getParent());
        Files.writeString(file, code);
    }
}

Output:

Output
app/Hidden.java:3: error: modifier private not allowed here
app/App.java:9: error: branchCode is not public in Account; cannot be accessed from outside package
app/App.java:10: error: owner has protected access in Account
app/Narrow.java:7: error: getBalance() in Narrow cannot override getBalance() in Account
    attempting to assign weaker access privileges; was public
app/Savings.java:9: error: owner has protected access in Account
bank/Teller.java:7: error: balance has private access in Account

Every line marked "error" in the sources was rejected, and every line marked "OK" compiled, since only errors are printed. Reading the errors one by one:

  • Teller is in the same package as Account, so it may read branchCode (package-private) and owner (protected), but not balance: private means the class itself only.
  • App is in another package and is not a subclass, so it can use only id and the public getBalance(). Notice the different wording: for package-private, javac says "is not public in Account; cannot be accessed from outside package".
  • Savings extends Account from another package. It may use owner on itself and through a Savings reference, but other.owner through a plain Account reference was rejected. This is the protected rule most people do not know: outside the package, a subclass can reach protected members only of objects of its own type, so it cannot use them to tamper with unrelated accounts.
  • Narrow tried to override the public getBalance() with a package-private method: "attempting to assign weaker access privileges". An override may keep or widen access, never narrow it, because code holding an Account reference must be able to call the method on any subclass.
  • private class Hidden at the top level is not allowed: there is no enclosing class it could be private to.

private is per class, and nestmates

A common belief is that private fields belong to one object. In fact, access is checked per class: code in a class can read the private fields of any instance of that class, and of any class nested in the same top-level class. The program compares two Money objects through their private fields and reads one from the enclosing class.

Java
public class PrivateScope {

    static class Money {
        private final long cents;           // private to the top-level class PrivateScope

        Money(long cents) {
            this.cents = cents;
        }

        // private is per class, not per object: another Money's field is accessible
        boolean sameAs(Money other) {
            return cents == other.cents;
        }
    }

    public static void main(String[] args) {
        Money a = new Money(500);
        Money b = new Money(500);
        System.out.println("a.sameAs(b): " + a.sameAs(b));

        // The enclosing class can read a nested class's private field too
        System.out.println("read from the outer class: " + a.cents);

        // Since Java 11 these are "nestmates": no hidden accessor methods are generated
        System.out.println("nestmates: " + PrivateScope.class.isNestmateOf(Money.class));
        System.out.println("nest host of Money: " + Money.class.getNestHost().getSimpleName());
    }
}

Output:

Output
a.sameAs(b): true
read from the outer class: 500
nestmates: true
nest host of Money: PrivateScope
  • sameAs read other.cents, another object's private field. This is how equals methods are normally written.
  • The outer class PrivateScope read a.cents, a private field of its nested class. A top-level class and all classes nested inside it share their private members.
  • Before Java 11, the compiler made this work by generating hidden accessor methods with names such as access$000. Java 11 (JEP 181) made the JVM aware of nestmates, so no accessors are needed. isNestmateOf and getNestHost expose this.

What private does not protect: leaked mutable objects

A private field only stops other code from naming the field. If a getter returns the object the field refers to, and that object can be changed, callers can change the class's internals anyway. The program gives a team a limit of 3 members, enforced in add, then breaks the limit through the getter.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LeakingInternals {

    // private fields are not enough if a getter hands out the mutable object itself
    static class LeakyTeam {
        private final List<String> members = new ArrayList<>();

        void add(String name) {
            if (members.size() >= 3) {
                throw new IllegalStateException("team is full");
            }
            members.add(name);
        }

        List<String> getMembers() {
            return members;                          // the caller gets the real list
        }
    }

    static class SafeTeam {
        private final List<String> members = new ArrayList<>();

        void add(String name) {
            if (members.size() >= 3) {
                throw new IllegalStateException("team is full");
            }
            members.add(name);
        }

        List<String> getMembers() {
            return Collections.unmodifiableList(members);   // a read-only view
        }

        List<String> snapshot() {
            return List.copyOf(members);                    // an independent copy
        }
    }

    public static void main(String[] args) {
        LeakyTeam leaky = new LeakyTeam();
        leaky.add("Ana");
        leaky.getMembers().add("Ben");
        leaky.getMembers().add("Cho");
        leaky.getMembers().add("Dev");                      // bypasses the size check
        System.out.println("leaky team: " + leaky.getMembers() + " (limit was 3)");

        SafeTeam safe = new SafeTeam();
        safe.add("Ana");
        List<String> view = safe.getMembers();
        List<String> copy = safe.snapshot();
        try {
            view.add("Ben");
        } catch (UnsupportedOperationException e) {
            System.out.println("safe team view: UnsupportedOperationException on add");
        }
        safe.add("Ben");
        System.out.println("view after add: " + view + ", snapshot: " + copy);
    }
}

Output:

Output
leaky team: [Ana, Ben, Cho, Dev] (limit was 3)
safe team view: UnsupportedOperationException on add
view after add: [Ana, Ben], snapshot: [Ana]
  • LeakyTeam.getMembers() returned the real list, so the caller added three names directly and the team ended up with four members, past its limit. The check in add was never consulted.
  • SafeTeam returns Collections.unmodifiableList(members), a read-only view: adding through it threw UnsupportedOperationException. The view still shows later changes made through add: it printed both Ana and Ben.
  • List.copyOf returns an independent unmodifiable copy, frozen at the moment it was taken: the snapshot still shows only Ana. Use a copy when the caller should not see later changes; use a view when it should and copying would be expensive.
  • The same applies to arrays, Date and any other mutable type: copy on the way in (in constructors) and on the way out (in getters), or use immutable types. The immutability page covers this in depth.

Reflection and the module system

Access modifiers are enforced by the compiler and the JVM, but reflection can ask to switch the check off. The program reads a private field of its own nested class, then tries the same on a private field of java.lang.String.

Java
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;

public class ReflectionAccess {

    static class Vault {
        private String secret = "1234";
    }

    public static void main(String[] args) throws Exception {
        // In your own code, reflection can switch off the private check
        Vault v = new Vault();
        Field f = Vault.class.getDeclaredField("secret");
        try {
            f.get(v);
            System.out.println("read without setAccessible: allowed (same nest)");
        } catch (IllegalAccessException e) {
            System.out.println("read without setAccessible: IllegalAccessException");
        }
        f.setAccessible(true);
        System.out.println("after setAccessible(true): " + f.get(v));

        // JDK internals are protected by the module system since Java 16 (JEP 396)
        Field value = String.class.getDeclaredField("value");
        try {
            value.setAccessible(true);
            System.out.println("String.value opened");
        } catch (InaccessibleObjectException e) {
            System.out.println("String.value: InaccessibleObjectException");
            System.out.println("  " + e.getMessage().substring(0, e.getMessage().indexOf(':')));
        }
    }
}

Output:

Output
read without setAccessible: allowed (same nest)
after setAccessible(true): 1234
String.value: InaccessibleObjectException
  Unable to make field private final byte[] java.lang.String.value accessible
  • The first read worked even without setAccessible: ReflectionAccess and Vault are nestmates, and reflection applies the same rule as compiled code. From an unrelated class it would have thrown IllegalAccessException.
  • setAccessible(true) switches the check off for classes in your own code, which is how serialization and dependency injection frameworks set private fields.
  • For JDK internals, it fails with InaccessibleObjectException. Since Java 9 the JDK is split into modules, and since Java 16 (JEP 396, made permanent by JEP 403 in Java 17) packages that a module does not open cannot be accessed by reflection. The --add-opens command-line option is the escape hatch.
  • Modules add a level above the four modifiers: a public class in a package that its module does not export is not accessible from other modules at all. See modules and reflection.

Choosing an access level

Start with the most restrictive level that works, and open up only when there is a reason, because narrowing access later breaks other people's code while widening it never does.

Typical access levels
MemberUsual levelWhy
FieldsprivateThe class controls its own state; constants may be public static final
Helper methodsprivateFree to change or remove
Classes used only inside a packagePackage-privateKeeps the public API small
Members a test in the same package must reachPackage-privateTests live in the same package in a separate folder
Hooks meant for subclassesprotectedPart of the contract for extenders; document them as such
Constructors of abstract classesprotectedOnly subclasses can call them anyway
The operations the class exists to providepublicThe class's API

Two more modifiers control a different question, how a member can be changed or inherited rather than who can see it: see final and static.