[statics] allowing static initializers in interfaces?

forax at univ-mlv.fr forax at univ-mlv.fr
Tue Dec 8 07:21:12 UTC 2020


----- Mail original -----
> De: "John Rose" <john.r.rose at oracle.com>
> À: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "Maurizio Cimadamore" <maurizio.cimadamore at oracle.com>, "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Mardi 8 Décembre 2020 08:08:28
> Objet: Re: [statics] allowing static initializers in interfaces?

> In my latest (and probably 100th) lap around this
> set of obstacles, I’ve used a workaround like the
> following:
> 
> interface Something {
>  default someMethod(int x) { return x * Private.SOME_CON; }
>  /*should be private*/ static final class Private {
>    private Private() { }
>    private static final int SOME_CON = 42;
>  }
> }
> 
> The private class can contain private nested classes,
> private static methods, and private constants, all
> inaccessible outside of the interface nest.  A good use
> of private nested classes would be classes which
> provide one or more standard implementations
> of the interface.
> 
> This pattern has the advantage of allowing a single-keyword
> upgrade when private classes are eventually allowed, and also
> a pretty small (though non-empty) API footprint today.

or you can write

interface Something {
 default int someMethod(int x) { return x * new Object() { private static final int SOME_CON = 42; }.SOME_CON; }
}

and the JIT will happily remove new Object() + pop.

and BTW, con is cunt in French, that why i urge my student to never use abbreviation :)

> 
> — John

Rémi

> 
>> ----- Mail original -----
>>> De: "John Rose" <john.r.rose at oracle.com>
>>> À: "Maurizio Cimadamore" <maurizio.cimadamore at oracle.com>
>>> Cc: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
>>> Envoyé: Mercredi 18 Novembre 2020 09:07:18
>>> Objet: Re: [statics] allowing static initializers in interfaces?
>> 
>>> +1 from me too, and generally to heal the rift.
>>> The inability to put private classes (and other “stuff”)
>>> in an interface makes it hard to support canonical
>>> algorithms in default methods, if they need auxiliary
>>> types.
>> 
>> yes,
>> another example, in the patch introducing the new random generator API currently
>> under review, there is this method
>> 
>>  default float nextFloat() {
>>    return (nextInt() >>> 8) * 0x1.0p-24f;
>>  }
>> 
>> which a good example of why we also need private static final fields in
>> interface.
>> 
>> Rémi


More information about the amber-spec-experts mailing list