Warnings

John Hendrikx john.hendrikx at gmail.com
Mon Dec 5 03:50:25 UTC 2022


On 04/12/2022 20:53, John Neffenger wrote:
> On 12/4/22 8:22 AM, John Hendrikx wrote:
>> - Avoiding indirect access to static methods and fields
>>
>>         class A { static final int ONE = 1; }
>>         class B { }
>>         class C extends B {
>>              int one = ONE;  // unqualified access to A.ONE
>>         }
>
> Did you mean the following?
>
>     class B extends A { }

Yes, my mistake.

>
> There's a related trap in this category: inaccessible members can be 
> unintentionally made public by an intermediate subclass. For example:
>
>     package pkg1;
>     interface A { static final int ONE = 1; } // ONE has package access
>
>     package pkg1;
>     public class B implements A { } // ONE is now public in B
>
>     package pkg2;
>     import pkg1.B;
>     class C extends B {
>         int one = ONE; // ONE is accessible in pkg2.C
>     }
>
> Through this chain, members with package access (not just constants) 
> can inadvertently end up in a public API. There are 423 occurrences of 
> this in the Java API. There's a fix in JDK 20 that should let us find 
> them in the JavaFX API, too. I don't think there's much we can do 
> about it except be aware of them.
>
> I was really surprised by this, but see the classes in the 'pkg1' and 
> 'pkg2' directories below for an example that you can compile and run:
>
> https://github.com/openjdk/jdk/tree/master/test/langtools/jdk/javadoc/doclet/testIndexInherited 
>

It is a bit unexpected indeed, I hadn't really thought about it that 
much. For methods it makes sense enough, as everything in an interface 
is always public and they are inherited and implemented in the 
implementation as public members. Those methods can be accessed simply 
because they're public, it doesn't matter that they came from an 
interface.  The static field however is not inherited or implemented in 
the sub type; perhaps it was not such a good idea to allow indirect 
access to static members in the first place.

Hopefully IDE's will get a warning for this soon as well.

--John


More information about the openjfx-dev mailing list