Local classes & sealed classes

Dan Smith daniel.smith at oracle.com
Tue May 5 21:50:01 UTC 2020


> On May 1, 2020, at 3:38 PM, Remi Forax <forax at univ-mlv.fr> wrote:
> 
> ----- Mail original -----
>> De: "Brian Goetz" <brian.goetz at oracle.com>
>> À: "daniel smith" <daniel.smith at oracle.com>, "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
>> Envoyé: Vendredi 1 Mai 2020 23:17:00
>> Objet: Re: Local classes & sealed classes
> 
>> Erring on the side of quick answers because time is getting tight.
>> 
>>> 1) A local class can extend a sealed class that lacks a 'permits' clause.
>>> 
>>> The implicit list of permitted subclasses will include all classes declared in
>>> the same compilation unit.
>>> 
>>> sealed class A {
>>>     void m() {
>>>         final class B extends A {}
>>>     }
>>> }
>>> 
>>> Note that the local class can't be declared 'sealed' or 'non-sealed'—see
>>> below—but can be declared 'final'.
>>> 
>>> There's nothing particularly wrong with this, other than the fact that it's
>>> impossible to rewrite it with an explicit 'permits' clause.
>>> 
>>> I can see it being a useful way to handle, say, an interface that declares a
>>> handful of factory methods to produce a limited set of implementations.
>> 
>> We already prohibit lambdas and anonymous classes from extending sealed
>> classes at all, inferred or not.  We didn't explicitly consider local
>> classes (oops), but I wouldn't like this behavior. If you can't write
>> down the permits clause, you shouldn't infer it. I think we should
>> exclude local classes from candidacy.
> 
> I agree, if the name of the class is not constant (stable), the compiler should try to added it in a permits clause.

The fact that some classes have unstable binary names is not an issue. Everything in the compilation unit gets recompiled at once, including the sealed superclass and the extending subclass. (You might be concerned about, say, Javadoc listing a local class among the permitted subclasses, which it really shouldn't, but it's the same problem with private member classes. Some sealed classes have publicly-exposed exhaustive lists of subclasses; others do not.)


More information about the amber-spec-observers mailing list