[statics] allowing static initializers in interfaces?
John Rose
john.r.rose at oracle.com
Tue Dec 8 07:08:28 UTC 2020
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.
— John
> ----- 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