More constraints on nesting that could be relaxed
Alan Malloy
amalloy at google.com
Wed Jan 22 18:19:03 UTC 2020
The recent thread about "cleaner nesting" reminded me of a related language
constraint that has caused me a bit of a headache recently, and I wonder if
we can clean it up at the same time.
Somewhat recently, interfaces have gained the ability to have private
methods, for use as helpers in implementing default methods. However, there
is currently no plan for private fields or private nested classes to be
allowed in those contexts, even private static final fields. I don't see
any particularly compelling reason for this: private fields made no sense
for interfaces in Java 1.0, but since interfaces can now have private
behavior, it makes sense for them to have private state to support that
behavior, or at the very least private constants.
For example, it seems like it should be totally fine to write:
interface Actor {
private static final Logger logger = new Logger();
default void act() {
logger.log("act not implemented");
}
}
But this is illegal because logger is not permitted to have the private
modifier. Instead, you have to either make the logger public (polluting the
namespace of inheriting classes and breaking encapsulation of your
interface), or else invent some public class that's allowed to hold a
private method (still polluting the namespace, but keeping the field
hidden):
interface Actor {
/** Do not use. */
public static final class Private {
private static final Logger logger = new Logger();
}
default void act() {
Private.logger.log("act not implemented");
}
}
Is this something we could include in the overall nesting reform plan?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20200122/69534fbe/attachment-0001.htm>
More information about the amber-spec-experts
mailing list