Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java access boundaries: private nests and protected receivers

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Java access control checks both the member declaration and the context of its use; inheriting a protected member does not make it publicly accessible through every receiver.

Download Java source kit

Java 8+. The program uses JDK classes and requires no preview flags.

Separate inheritance from access

A delivery adapter extends a base class in another package. The adapter can access an inherited protected field through its own compatible receiver, but a general base-typed object does not automatically qualify. Code that worked inside the base package can therefore fail after it is moved into the adapter package.

Package-private access has no modifier. A child class in a different package cannot use that access as if it were protected. Public access also depends on the enclosing type being accessible; a public method on an inaccessible implementation type is not a substitute for a public interface.

Private members are accessible within the enclosing nest of classes. This program uses two nested classes that belong to one top-level declaration. It proves that case; it does not prove that any unrelated class in the same package can read the private field. The downloadable access-packages fixture checks the cross-package protected cases with both successful and rejected compilations.

Review the boundary before changing visibility

If a consumer needs a delivery status, expose a status operation with a return contract. Publishing the mutable internal queue merely to make one compiler error disappear lets callers bypass the adapter’s invariants. A package layout is useful when it separates ownership, not when every member is made public to remove friction.

Working program

Java
public class NestAccessReceipt {
    static class Receipt { private final int accepted = 7; }
    static class Audit { static int read(Receipt receipt) { return receipt.accepted; } }
    public static void main(String[] args) { System.out.println(Audit.read(new Receipt())); }
}

Output

Output
7

Costs and boundaries

The field access itself is constant work. Package and access decisions are checked when code is compiled and linked; they are not collection traversal costs. The multi-file kit includes a subclass in another package and verifies that a base-typed protected receiver is rejected.

Common Mistakes

  • Being in a subclass does not grant arbitrary cross-package protected access.
  • An unrelated same-package class does not share a private nest.
  • Visibility is not a thread-safety rule.

Read next

Access modifiers, Package layout.

java
access-packages
Storage details