Accessibility of classes nested in local classes
Dan Smith
daniel.smith at oracle.com
Mon Jan 4 19:10:51 UTC 2021
javac has longstanding behavior, apparently unspecified, to reject accessibility modifiers on classes nested within an anonymous or local class. The changes involved in supporting statics inside of local classes have drawn attention to this behavior.
void m() {
class Local {
private class C1 {} // error
class C2 {}
protected class C3 {} // error
public class C4 {} // error
class Inner {
private class D1 {} // error
class D2 {}
protected class D3 {} // error
public class D4 {} // error
}
}
}
There's nothing in 8.1.1, 14.3, 15.9.5, or 8.5 to suggest this behavior. (There's a rule about modifiers on a local class declaration itself, but nothing about its members.)
In practice, members of local classes are essentially private anyway—there is no way to refer to them outside of the local class's enclosing method. So the access modifiers don't seem that useful. But they do affect things like inheritance (local class B extends local class A) and reflection. And while this same argument applies to fields, javac allows unrestricted use of field access modifiers inside local classes.
I think the appropriate resolution is to treat this as a javac bug and remove the access modifier restriction. Any reasons not to do so?
More information about the amber-spec-experts
mailing list