Sub topic 10
Private access between nested and enclosing classes
This chapter assumes you can write and compile basic Java classes. It also assumes you know the four access modifiers and the difference between static nested classes and inner classes. If you can read Outer.Inner and outer.new Inner() without stopping, you are ready.
The rule: private is scoped to the top-level class
Most Java developers learn that private means "visible only inside this class". That is slightly wrong. The Java Language Specification (JLS 6.6.1) says a private member is accessible within the body of the top-level class that encloses its declaration.
A nested class is part of the body of its top-level class. So all of these are legal:
- The enclosing class reads and writes private members of its nested classes.
- A nested class reads and writes private members of its enclosing class.
- Two sibling nested classes read and write each other's private members.
- Deeply nested classes reach private members at any level of the same top-level class.
This holds for static nested classes, inner classes, local classes, and anonymous classes.
A worked example
public class Vault {
private int secret = 42;
private static class Door {
private final String label;
private Door(String label) { this.label = label; }
private int peek(Vault v) { return v.secret; }
}
private static class Window {
int labelLength(Door d) { return d.label.length(); }
}
public static void main(String[] args) {
Door d = new Door("front"); // private constructor
System.out.println(d.label); // front
System.out.println(d.peek(new Vault())); // 42
System.out.println(new Window().labelLength(d)); // 5
}
}Four private accesses happen here:
Vault.maincalls the private constructor ofDoor.mainreads the private fieldd.label.Door.peekreads the private fieldv.secretof the enclosing class.Window.labelLengthreads the private field of its siblingDoor.
None of this needs getters, and none of it widens a modifier. That is why a private nested class is a common way to give one class a helper with full access to its internals, as in the RingIterator example from the earlier chapters.
Access needs a reference to the object
The rule grants permission. It does not give you an instance. A static nested class has no enclosing instance, so it must be handed one. That is why Door.peek takes a Vault parameter. An inner (non-static) class has a hidden reference to its enclosing instance, so it can write secret directly.
public class Account {
private int balance = 100;
static class Auditor {
int read(Account a) { return a.balance; } // legal: same top-level class
// int bad() { return balance; } // error: no enclosing Account instance
}
class Statement {
int read() { return balance; } // legal: uses Account.this.balance
}
}The compiler error for bad() is about a non-static field in a static context. It is not an access error. Keep the two ideas apart: permission to see a name, and an object to apply it to.
What the boundary excludes
The boundary is the top-level class, not the source file and not the package.
| Situation | Private access allowed? |
|---|---|
| Outer class to a nested class's private member | Yes |
| Nested class to the outer class's private member | Yes |
| Sibling nested classes | Yes |
| Two top-level classes in the same file | No |
| Two top-level classes in the same package | No |
| A subclass of the outer class, declared outside it | No |
A second gotcha: private members are not inherited. Suppose a nested class extends its own outer class. Then sub.x does not compile when x is a private field of the outer class, because x is not a member of Sub. The compiler looks for x as a member of the type of the expression sub. Cast to the declaring type to reach it:
public class Base {
private int x = 7;
static class Sub extends Base {
int read(Sub sub) {
// return sub.x; // error: x is not a member of Sub
return ((Base) sub).x; // legal: x is a member of Base
}
}
public static void main(String[] args) {
System.out.println(new Sub().read(new Sub())); // 7
}
}The same effect applies to type variables. If T extends Base, then t.x fails inside Base, but ((Base) t).x works.
Which design choices this enables
Because the boundary is the top-level class, you can:
- Keep fields
privateand still share them with a helper class, such as a builder, an iterator, or a node class. - Make the helper itself
private, so callers never see its type. - Avoid public or package-private "back door" accessors that exist only for one helper.
The cost is that the top-level class is the real unit of encapsulation. Everything nested inside it can see everything else. A large outer class with many nested classes has weaker internal encapsulation than the word private suggests. If a nested class grows large and wants independent invariants, consider moving it to its own top-level class and exposing a narrow interface.
How the access is implemented
The JVM itself has always treated private as "only inside the same class". Nested classes compile to separate class files (for example Vault$Door.class), so a direct access from one class file to a private member of another would be rejected. The compiler had to bridge this gap, and the bridge changed in Java 11.
Before Java 11: synthetic accessors
The compiler generated hidden package-private static methods, usually named access$000, access$100, and so on, in the class that owned the private member. Code in the other class called those methods instead. For a private constructor, the compiler added an extra synthetic constructor taking a dummy parameter of an anonymous class type, which often produced an otherwise empty Outer$1.class file.
This worked but had side effects:
- Extra methods bloated the class files.
- Stack traces and profilers showed
access$000frames. - Reflection showed synthetic members that were not in your source.
Java 11 and later: nestmates
JEP 181 added nest-based access control. Each class file records its relationship in two attributes:
NestHostin each member, naming the top-level class.NestMembersin the host, listing every nested class.
Classes with the same nest host are nestmates, and the JVM lets nestmates access each other's private members directly. No accessor methods are generated. You can inspect nests with reflection:
public class Nests {
static class A { private int a; }
static class B { }
public static void main(String[] args) {
System.out.println(A.class.getNestHost().getSimpleName()); // Nests
System.out.println(A.class.isNestmateOf(B.class)); // true
System.out.println(Nests.class.getNestMembers().length); // 3
}
}getNestMembers() includes the host itself, so the three entries are Nests, A, and B. Reflection access checks also honor nestmates from Java 11 on, so code in one nestmate can use Field.get on a private field of another without setAccessible(true).
To see the compiled form, run javap on a class file:
javap -p -v 'Vault$Door.class'Look for the NestHost: class Vault line near the end of the output. Compiled with a release below 11, the same command shows access$000-style methods in the owning class instead.
Common errors and pitfalls
- Assuming a second top-level class in the same file is a nestmate. It is not.
class Helperdeclared afterpublic class MaininMain.javacannot seeMain's private members. - Forgetting the instance. Permission to see
balancedoes not give you anAccount. Static nested classes need a parameter or a field holding one. - Using
sub.xfor an inherited-looking private field. The field is not inherited. Cast to the declaring class. - Treating
privateas a security boundary. Nested access means a class's privates are visible to a large amount of code. Reflection withsetAccessible(true)can also reach them, subject to module encapsulation. - Targeting older runtimes. If you compile for Java 8 (
--release 8), you get synthetic accessors even on a newer JDK. This matters when you read stack traces or reflect on members.
Exercise
A file Shop.java declares public class Shop { private int stock = 5; } and, below it, a second top-level class class Auditor { int read(Shop s) { return s.stock; } }. Does it compile? Then move Auditor inside Shop as a static nested class. What changes, and what does the JVM do differently in Java 8 versus Java 11 or later to make that access work?
Show answer
As written it does not compile, because stock is private and Auditor is a separate top-level class, so it is outside the boundary. Moved inside Shop as static class Auditor, the same read(Shop s) method compiles, because private access is scoped to the top-level class Shop. In Java 8 the compiler generates a synthetic accessor such as access$000 in Shop that Auditor calls. In Java 11 or later, Shop and Shop$Auditor are nestmates (recorded by the NestHost and NestMembers attributes), so the JVM allows the direct field access and no accessor is generated.