Consider the following code:
public class A {
public static void main(String[] args) {
Runnable test1 = ((I)(new I() {}))::test; // compiles OK
private
methods are not inherited (Closest I found so far is: JLS6.6-5: "[A private class member] is not inherited by subclasses"). That means that you can not access a private method, from a subtype (because it simply does not 'have' that method). For instance:
public static void main(String[] args) {
I1 i1 = null;
I2 i2 = null;
i1.test(); // works
i2.test(); // method test is undefined
}
interface I1 {
private void test() {}
}
interface I2 extends I1 {}
That also means that you can not directly access the test
method through the type of an anonymous subclass.
The type of the expression:
(new I() {})
Is not I
, but actually the non-denotable type of the anonymous subclass, so you can't access test
through it.
However, the type of the expression:
((I) (new I() {}))
is I
(as you explicitly cast it to I
), so you can access the test
method through it. (just like you can do ((I1) i2).test();
in my above example)
Similar rules apply to static
methods, as they are also not inherited.