With interfaces structure like this:
Why does not A-D-F yield an error since it is a cycle?
Note: An arrow A->B means A extends B
I tried to interpret your diagram in code as follows:
interface A extends B, C, D { }
interface B { }
interface C { }
interface D extends F{ }
interface E extends F{ }
interface F extends A{ }
And the compiler fails with the error:
java: cyclic inheritance involving A
So, as expected, cyclic inheritance is not allowed.
The error goes away if F
does not extend A
.
It does yield an error, have you tried it?
interface A extends D {} // error on this line: The hierarchy of the type A is inconsistent
interface D extends F {} // error on this line: The hierarchy of the type D is inconsistent
interface F extends A {} // error on this line: Cycle detected: a cycle exists in the type hierarchy between F and A
I have seen the following insane usage:
interface I {
static final I CONSTANT = new C();
...
}
class C implements I {
}
The reason that this works, is that the .class (like a binary .obj) contains symbolic information on its imports. So a .java can be compiled to a .class. And then the linkage against other .class files may be done.
For the same reason (loose linkage) execution may fail, when compiled with a different version of a jar than at run-time.
Some compilers might balk at specific cycles though.
One addition though
If one interface uses constants from another interface, upon compilation those constants are stored in the .class file, and in effect the imports disappear. In that case there is at least one compiler, that does not detect dependencies, and a cycle may be broken. This might even lead to wrong, stale constants; an anti-pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With